首页 > 解决方案 > 为我的 jQuery 创建循环时遇到问题

问题描述

我有这个有效的脚本。到目前为止,它为最后一组正确更改了图像,我想把它放在我有 m=k 的循环中,但它不起作用

for (m = 0; m < k; ++m) {
    <script>
    $(function() {
         var m = 1;
         var resultb = $('[id^=input_]').filter(function () {
             return this.id.match(/input_\d+$/); //regex for the pattern "input_ followed by a number"
         }).length;
         var  k = resultb;
         m = k;

         $("#input_"+m).change(function() {
             var val = $("#input_"+m+" option:selected").text(); 
             var valval = $("#input_"+m+"option:selected").val(); 
             var n = val.indexOf('(');
             val = val.substring(0, n != -1 ? n : val.length);
             var img_option='images/sample/'+val+'.jpg';
             if ($("#input_"+m+" option:selected").val() > 0)   
                 $("a.lb:first").html( "<img src="+ img_option+">");
             $('a.lb:first img').css({'width' : '350px' });
             $('a.lb:first img').addClass( "img-fluid" );
         });
    });
    </script>

标签: javascriptjquery

解决方案


您的m值似乎是基于 1 的,因此您的循环将要从1.

话虽如此,您根本不需要for循环。只需选择您想要的元素:

$(function() {
   const inputs = $('[id^=input_]').filter(function () {
      return this.id.match(/input_\d+$/); //regex for the pattern "input_ followed by a number"
   });
   inputs.on('change', function() {
      // I'm assuming that `#input_X` is actually a `<select>`, not an `<input>`
      // You should probably adjust your naming convention to be less confusing
      let text = this.options[this.selectedIndex].text;
      let value = this.options[this.selectedIndex].value;

      let parenthesis = text.indexOf("(");
      if( parenthesis > -1) text = text.substring(0, parenthesis);

      let source = `images/sample/${text}.jpg`;
      if( value > 0) $("a.lb:first").html(`<img src="${source}" style="width: 350px" class="img-fluid" />`);
   });
});

你会注意到我给你的变量取了更合理的名字,使用let起来也const更合适,而且通常把代码整理得尽可能干净和易于理解。


推荐阅读