在为我的jQuery创建循环时遇到问题

时间:2020-06-07 20:44:24

标签: javascript 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>

1 个答案:

答案 0 :(得分:2)

您的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" />`);
   });
});

您会注意到,我给变量赋予了更合理的名称,在更合理的情况下使用了letconst,并且通常将代码整理得尽可能整洁和易于理解。