附加选择的 Change() 不起作用

2023-12-04

我有 jQuery 函数来更改选择元素:

$("#category").change(function(){
    $("table[id=advance_search]").append("<tr id='item_type'></tr>");
    $("tr[id=item_type]").append("<td class='field_input'><select id='type'><option value='1'>One<option><option value='2'>Two<option></select></td>");
});

$("tr[id=item_type]").children(".field_input").delegate("select[id=type]", "change", function() {
    console.log("change");
});

当我改变值时select#type,字符串“change”不显示在控制台中。 谁能帮我?


已编辑,用于添加<td class='field_input'>作为孩子$("tr[id=item_type]")


这里的问题是因为change()(以及所有其他事件处理程序快捷方式)在页面加载时绑定,但您的元素在此之后动态添加。相反,你需要使用delegate()在附加该元素后将事件附加到该元素。

$("tr[id=item_type]").delegate("select[id=type]", "change", function() {
    console.log("change");
});

或者,如果您使用的是 jQuery 1.7+,您可以使用on():

$("tr[id=item_type]").on("change", "select[id=type]", function() {
    console.log("change");
});

您可能想要修改select不过,您在此处附加的元素,因为它有一个 ID,如果多次附加该 ID,则该 ID 很容易被复制,从而导致页面无效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

附加选择的 Change() 不起作用 的相关文章