通过一系列按钮点击显示图像

3

我正在尝试建立一个功能非常基础的网站。基本上,该网站应包含各种按钮,并根据单击哪个系列的按钮来显示图像。不幸的是,我的网站开发经验非常有限(或者可以说没有),但我在stackoverflow上找到了一些代码,这些代码在某种程度上可以工作。基于此,我想以一种允许我实现所需功能的方式改变代码。

以下是网站预期外观:

supposed to look like this

正如您所看到的,该网站包含从A-D和0-9的各种按钮。按钮单击将记录在下面的字段中,一旦输入与文件名匹配的组合,就会显示图像。

以下是代码:

              
    $(document).ready(function() {
      /**
       * Select the buttons.
       * The $display and $clickedButtons are just to output
       * the values that are stored.
       */
      const $buttons = $('.button');
      const $display = $('#display');
      const $clickedButtons = $('#clicked-buttons');
      const $reset = $('#reset');
      $reset.on('click', function() {
        values = [];
        $clickedButtons.text(values);
      });
      
      /**
       * Array which tracks your clicked buttons.
       * If a button is clicked, the value of that button
       * should be added to this array. The combination
       * of the values will then later represent the key.
       */
      var values = [];
      
      /**
       * Listen for the click event on all the buttons.
       * When clicked, get the value of that clicked button
       * and add that to the values array.
       * After that the clicked button values will be combined
       * to form a single key and check if that key matches 
       * a combination. If there is a match the content should
       * be anything other than undefined.
       */

      $buttons.on('click', function() {
        // This is the currently clicked button.
        const $button = $(this);
        
        // Get the value of the button.
        const value = $button.val();
        
        // If there already are 15 previously clicked buttons,
        // then empty the array, so we can start a new combination.
        if (values.length === 15) {
          values = [];
        }
        
        // Now add the newly clicked value.
        values.push(value);
        
        // This will output the current values in the array.
        $clickedButtons.text(values);
        
        // Transform the array into a single string.
        // This will be the key to select content.
        // ["1", "2", "3"] becomes "123".
        const key = values.join('');    
        
        // Check if key has a match in the combinations object.
        $display.attr('src', 'output/' + key + '.png');
      });
    }); 

现在来说我的问题:代码要求按照图片名称的顺序精确点击按钮组合。例如,输入A-B-C-1-2-3将显示ABC123.png。但是,为达到我的目的,即使输入为31B2AC或这6个输入的任何其他组合,代码也需要显示ABC123.png。我已经研究了“排序”的选项,但这反而会产生另一个问题,因为有些图片的命名方式如D9B6C4.png这样,因此没有适用的逻辑(如字母表顺序或数值)可用于排序算法的运行。但是,文件夹中的每个图像都是唯一的,因此当存在ABC123.png时,BCA321就不存在。
我需要脚本遍历所有图片并找到包含输入的所有字母和数字的唯一图片,无论它们的顺序如何。这是否可能?我该如何实现?
///////// 编辑 ////////
我尝试添加显示、跟踪已点击按钮以及删除按钮:
所以不太确定为什么什么都没用。输入既没有显示在适当的字段中,也没有显示图片...

       
  const $buttons = $('.button');
  const $display = $('#display');
  const $clickedButtons = $('#clicked-buttons');
  const $removeButton = $('#remove-button');    
  const values = [];
        
var imgs = ["ABC123.png", "1A2B4C.png", "ABC132.png", "123ABC.png"];

function case_insensitive_comp(strA, strB) {
  return strA.toLowerCase().localeCompare(strB.toLowerCase());
}

function reSortFiles() {
  var all = {};
  imgs.forEach(function(a) {
    d = a.split(".");
    img = d[0].split("");
    img = sortStr(img);
    img = img.join("");

    all[img] ? all[img].push(a) : all[img] = [a];
  });

  return all;
}

function sortStr(str) {
  return str.sort(case_insensitive_comp)
}

function tryCombination() {
    // This will output the current values from the array.
    $clickedButtons.text(values);        
    
const key = values.join('');  
        
allImages = reSortFiles()
console.log(allImages)


buttons = document.querySelectorAll("button")

clicked = "";

buttons.forEach(function(btn) {
  btn.addEventListener("click", function(e) {
    clicked += e.target.dataset.value;
    clicked_s = sortStr(clicked.split("")).join("")
    console.log(clicked, clicked_s)
    img = allImages[clicked_s]
    if (img) {
      console.log("Found: ", img.join(","))
      clicked=""; 
    }
  });
});
   
.container {
  display: grid;
  grid-template-rows: auto auto;
  grid-template-columns: 200px 1fr;
  grid-gap: 1em;
  border: 1px solid #d0d0d0;
  background-color: #f7f7f7;
  padding: 1em;
  border-radius: 5px;
}

.buttons {
  grid-area: 1 / 1 / 2 / 3;
}

#display {
  grid-area: 2 / 1 / 3 / 2;
  width: 200px;
  height: 200px;
  background-color: #d0d0d0;
  border-radius: 5px;
}

#clicked-buttons {
  grid-area: 2 / 2 / 3 / 3;
  display: block;
  background-color: #d0d0d0;
  border-radius: 5px;
  padding: 1em;
  margin: 0;
}

#remove-button {
  grid-area: 1 / 2 / 2 / 3;
}

.hidden {
  opacity: 0;
  visibility: hidden;
}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="buttons">
    <button class="button" id="1" value="1" >1</button>
    <button class="button" id="2" value="2" >2</button>
    <button class="button" id="3" value="3" >3</button>
    <button class="button" id="4" value="4" >4</button>
    <button class="button" id="5" value="5" >5</button>
    <button class="button" id="6" value="6" >6</button>
  </div>
  <img id="display" class="hidden">
  <button id="remove-button">Remove last input</button>
  <code id="clicked-buttons"></code>
</div>


1
我认为解释一下图像文件的命名方案会很有帮助。我的意思是,你是如何选择一个文件,比如“ABC123”和“D9B6C4”存在,但“BCA321”不存在呢? - user79161
1
你们有任何服务器端技术可以扫描包含图片的文件夹吗?你们有所有图片的完整列表吗?(由“解析图片”所暗示)尝试每个6个选定字母的组合将需要720次尝试,7个字母则需要5040次……12个字母则需要479,001,600次。如果你们没有现成的列表,那么使用HTTP请求尝试每一个将是不可行的。 - freedomn-m
1
嘿,谢谢你提醒我。我已经修复了标签。该网站是本地托管的,不应该被发布。因此,没有技术在扫描图像。但是,完整的图像列表确实存在。 - quarantinho
1
如果您已经有一个列表,那么它就是将正则表达式与"[" + values.join('') + "]\.png"或者regex = "(" + values.join('|') + "){" + values.length + "}"进行匹配的情况。由于您的代码限制为15个字符,不清楚"A1.png"是否会匹配"ABC123"或文件名是否必须与所选字符的长度相同。 - freedomn-m
1
在“src=”之前,您可以设置一个现有值的数组,并通过循环遍历该数组并执行正则表达式比较,直到找到匹配项。这可能不是最有效的方法,但应该可以让您入门。如果我以后有时间且没有其他人处理,我会编写一些代码。抱歉,现在没时间。 - freedomn-m
显示剩余4条评论
1个回答

2
这是我的工作解决方案,虽然有点hacky。
将所有图像以文件名的形式加载到数组中。
然后循环遍历所有文件,并创建一个对象,其中排序后的名称为键,文件名为值。这样,无论图像的命名方式如何,它们都将具有类似999XXX的键。
然后只需要获取按钮点击事件并对其字符串进行排序,直到该字符串存在为止。

var imgs = ["ABC123.png", "1A2B4C.png"];

function case_insensitive_comp(strA, strB) {
  return strA.toLowerCase().localeCompare(strB.toLowerCase());
}

function reSortFiles() {
  var all = {};
  imgs.forEach(function(a) {
    d = a.split(".");
    img = d[0].split("");
    img = sortStr(img);
    img = img.join("");

    all[img] = a;
  });

  return all;
}

function sortStr(str) {
  return str.sort(case_insensitive_comp)
}

allImages = reSortFiles()

buttons = document.querySelectorAll("button")

clicked = "";

buttons.forEach(function(btn) {
  btn.addEventListener("click", function(e) {
    clicked += e.target.dataset.value;
    clicked = sortStr(clicked.split("")).join("")
    img = allImages[clicked]
    if (img) {
      console.log(img)
    }
  });
});
<button type="button" data-value="A">A</button>
<button type="button" data-value="B">B</button>
<button type="button" data-value="C">C</button>
<button type="button" data-value="1">1</button>
<button type="button" data-value="2">2</button>
<button type="button" data-value="3">3</button>

版本支持多个。

var imgs = ["ABC123.png", "1A2B4C.png", "ABC132.png", "123ABC.png"];

function case_insensitive_comp(strA, strB) {
  return strA.toLowerCase().localeCompare(strB.toLowerCase());
}

function reSortFiles() {
  var all = {};
  imgs.forEach(function(a) {
    d = a.split(".");
    img = d[0].split("");
    img = sortStr(img);
    img = img.join("");

    all[img] ? all[img].push(a) : all[img] = [a];
  });

  return all;
}

function sortStr(str) {
  return str.sort(case_insensitive_comp)
}

allImages = reSortFiles()
console.log(allImages)


buttons = document.querySelectorAll("button")

clicked = "";

buttons.forEach(function(btn) {
  btn.addEventListener("click", function(e) {
    clicked += e.target.dataset.value;
    clicked_s = sortStr(clicked.split("")).join("")
    console.log(clicked, clicked_s)
    img = allImages[clicked_s]
    if (img) {
      console.log("Found: ", img.join(","))
      clicked=""; 
    }
  });
});
<button type="button" data-value="A">A</button>
<button type="button" data-value="B">B</button>
<button type="button" data-value="C">C</button>
<button type="button" data-value="1">1</button>
<button type="button" data-value="2">2</button>
<button type="button" data-value="3">3</button>
<button type="button" data-value="4">4</button>


感谢您的出色工作。我现在意识到,在制定脚本应该实际实现什么时,我犯了一个错误,并且一旦按钮值由多个字母/数字组成,我将遇到问题。这实际上会导致文件夹中的某些图像包含不同顺序的相同字符,例如AbAcAd413.png和AdAcAb413.png都可能存在,而此脚本将失败。是否有可能进行排序,例如AbAcAd保持此顺序而不被拆分为单独的字母? - quarantinho
1
通过提前生成键值对,这比正则表达式高效得多。如果可以有多个具有相同键的值(上面的注释),那么您只需要将all[img]=a的小更改为all[img] ? all[img].push(a) : all[img] = [a];,并将最后一个console.log更改为console.log(img.join(",")) / 您的最终输出将具有多个图像。 - freedomn-m
厉害啊!有没有办法像我在我的原始帖子中提供的解决方案一样将console.log实现为可见字段,并且让图像实际显示而不是仅记录它?我尝试了一些组合代码,但好像卡在某个地方了。 - quarantinho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接