附加选择的change()不起作用 [英] change() for appended select doesn't work

查看:100
本文介绍了附加选择的change()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery函数,用于更改select元素:

I've jQuery function on change for a select element:

$("#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"未显示在控制台中. 谁能帮我?

When I change value on select#type, string "change" doesn't show in console. Can anyone help me?

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

Edited, for adding <td class='field_input'> as children of $("tr[id=item_type]")

推荐答案

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

The problem here is because change() (and all other event handler shortcuts) are bound on page load, yet your element is added dynamically well after this. Instead you need to use delegate() to attach the events to this element after it's appended.

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

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

Or, if you're using jQuery 1.7+ you can use on():

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

不过,您可能想要修改要在此处添加的select元素,因为它具有ID,如果多次添加,则很容易复制该ID,从而使页面无效.

You may want to amend the select element you're appending here though, as it has an ID, which could be easily duplicated if it's appended multiple times, which would render the page invalid.

这篇关于附加选择的change()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆