jQuery .change() 仅在第一个更改时触发

3
这是我的代码:
$.each (t.config.industry, function (i, v) {
    $(v).change(function () {
        console.log("Industry change!");
    });
});

t.config.industry 是一个 <select> id 的数组。例如:t.config.industry: ["#W2549_Sl", "#W2601_Sl", "#W2654_Sl"] 我的页面上有几个 <select> 框,我正在对它们进行跟踪。每当它们中的任何一个发生变化时,我都想触发一些操作。

显然,我想做的不仅仅是 console.log,但为了这篇文章的简单明了,我将限制在这个方面。在我的网站上,console.log 只打印一次,即在第一次更改后。在下拉菜单的后续更改中,它不会再次触发。

有人以前遇到过这种情况吗?

注意:我无法更改 HTML 标记。


如果没有看到一些标记,它可能有点难以解密,但是您正在一个each函数中包含更改。每个通常为批处理中的每个元素应用一次该函数,我从未在每个函数中嵌套更改函数。 - Jay Blanchard
标记只是一堆选择框。但我不能改变标记。很难解释,但我被标记卡住了。 - Jesse Atkinson
6个回答

4

我曾经遇到过这种行为,当多个选择元素的ID不唯一时会发生。 为了解决我的问题,我只需删除ID、定义一个类,并修改jQuery选择器以使用指定的类。例如:

    <select class="some_value" some_id="<%= some[:id] %>">

    $(".some_value").change(function() {
        var some_id = $(this).attr("some_id");
        alert('some_id: ' + some_id);
    });

坦白说,我认为这种行为是jQuery中的一个bug。为什么它会在第一次成功后失败呢?

1
如果您可以为要监视的每个选择元素添加一个公共类,那么这将极大地简化您的代码。尝试使用以下代码(需要jQuery 1.7以上版本才能使用on方法):
$(document).on('change','select.monitorme', function() {
    console.log($(this).attr('id')+' changed!');
});

$.each (t.config.industry, function (i, v) {
    $(v).change(function () {
        $(this).addClass('monitorme'); // or just add the class to your markup
    });
});

0

对于asp.net,在我的项目中它正常工作。

<asp:DropDownList ID="txtvisitname" AutoPostBack="true" class="txtno" AppendDataBoundItems="true" 
    runat="server" onchange="return selectChange()">
    <asp:ListItem Text="--SELECT--" Value="0" />
    <asp:ListItem Text="VISIT1" Value="VISIT1" />
    <asp:ListItem Text="VISIT2" Value="VISIT2" />
    <asp:ListItem Text="VISIT3" Value="VISIT3" />
    <asp:ListItem Text="VISIT4" Value="VISIT4" />
    <asp:ListItem Text="VISIT5" Value="VISIT5" />
    <asp:ListItem Text="Unscheduled  VISIT" Value="Unscheduled  VISIT" />
</asp:DropDownList>

功能:

selectChange() {
    if ($("[id*=txtvisitname]").val() == "Unscheduled  VISIT") {
        $(".other").show();
    } else {
        $(".other").hide();
    }
}

0

你需要在这个选择器中,在 v(你的 id)前面添加 # 才能使其生效。

$.each(t.config.industry, function (i, v) {
   $("#" + v).change(function () {
      console.log("Industry change!");
   });
});

t.config.industry 是我所有选择框 ID 的数组。 - Jesse Atkinson
@JesseAtkinson 已更新,请尝试 :-) 如果仍然无效,请在您的问题中发布数组的实际内容。 - Manse

0

尝试以一种HTML的方式重写它

        <select id="main_industry">
          <?foreach ($industry as $item ){?>
          <option value="<?=$item['id']?>"><?=$item['title']?></option>
          <?}?>
        </select>

JavaScript

   $('#main_industry').change(function() {
      // your stuff here
      console.log ($(this).val());
   }

-2
你似乎在每个选项上都设置了监听器。只需将其放在选择器上即可!

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