jQuery.change()只在第一次更改时触发

jQuery .change() only fires on the first change

本文关键字:第一次 change jQuery      更新时间:2023-09-26

这是我的代码:

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

CCD_ 1是CCD_。t.config.industry: ["#W2549_Sl", "#W2601_Sl", "#W2654_Sl"]我在页面上有几个<select>框,我正在跟踪它们。任何时候他们中的任何一个改变,我都想解雇一些人。

显然,我想做的不仅仅是console.log,但为了这篇文章,我将仅限于此。在我的网站上,console.log只在第一次更改时打印一次。在<select>下拉菜单的后续更改中,它不会启动。

有人见过这个吗?

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

当多个select元素的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。为什么它要一次成功,然后失败?

如果您可以为要监视的每个select元素添加一个公共类,这将极大地简化您的代码。试试这个(on方法需要jQuery 1.7):

$(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
    });
});

尝试用这样的方式重写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());
   }

您需要在v(您的id)之前添加#,以便此选择器工作

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

对于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();
    }
}

您正在为每个选项设置侦听器。请只选择它!