我用 jquery Ajax 动态生成一个下拉列表,生成下拉列表的 id
是 specificationAttribute
。我想为生成的新标签创建添加事件 (specificationAttribute
) ,为此我在 window.load
中创建了 Belowe script
:
$(document).on('change', '#specificationattribute', function () {
alert("Clicked Me !");
});
但它不起作用。
我尝试了更多方式,例如 click
、live
但我无法得到任何结果。
来自 fiddle 的代码:
$(window).load(function () {
$("#specificationCategory").change(function () {
var selected = $(this).find(":selected");
if (selected.val().trim().length == 0) {
ShowMessage('please selecet ...', 'information');
}
else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: { categoryId: categoryId, controlId: 'specificationattribute' },
type: 'POST',
success: function (data) {
$('#specificationattributes').html(data);
},
error: function (response) {
alert(response.error);
}
});
}
});
$(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});
}
最佳答案
您的 fiddle 有语法错误。由于下拉列表会生成一个选择,因此我们使用一个。
对于我的回答,我使用了这个 HTML,稍后会详细介绍:您的代码中的内容不匹配
<select id="specificationAttribute" name="specificationAttribute">
</select>
代码已更新:(查看内联评论,有些是建议,有些是错误)
$(window).on('load', function() {
$("#specificationCategory").on('change',function() {
var selected = $(this).find(":selected");
// if there is a selection, this should have a length so use that
// old: if (selected.val().trim().length == 0) {
if (!selected.length) { // new
// NO clue what this is and not on the fiddle so commented it out
// ShowMessage('please selecet ...', 'information');
alert("select something a category");// lots of ways to do this
} else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: {
categoryId: categoryId,
controlId: 'specificationattribute'
},
type: 'POST',
success: function(data) {
// THIS line id does not match my choice of specificationAttribute so I changed it
$('#specificationAttribute').html(data);
},
error: function(response) {
alert(response.error);
}
});
}
});
// THIS should work with the markup I put as an example
$(document).on('change', '#specificationAttribute', function() {
alert("changed ");
});
});// THIS line was missing parts
关于javascript - 更改事件不适用于动态生成的元素 - Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806979/