我为select元素改变了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]",function() {
console.log("change");
});
或者,如果您使用的是jQuery 1.7,则可以使用on():
$("tr[id=item_type]").on("change","select[id=type]",function() {
console.log("change");
});
您可能希望修改您在此处附加的select元素,因为它有一个ID,如果多次附加,可能很容易重复,这会使页面无效.