Javascript 使用.after()方法添加的jquery元素不会触发事件
代码如下:Javascript 使用.after()方法添加的jquery元素不会触发事件,javascript,jquery,html,jquery-after,Javascript,Jquery,Html,Jquery After,代码如下: <s:file name="upload" id="upload"></s:file> $('input[id^="upload"]').change(function(){ alert("aa"); $(this).after('<input type="file" name="upload_3" id="upload_3"/>'); alert($("#upload_3").attr("na
<s:file name="upload" id="upload"></s:file>
$('input[id^="upload"]').change(function(){
alert("aa");
$(this).after('<input type="file" name="upload_3" id="upload_3"/>');
alert($("#upload_3").attr("name"));
});
$('input[id^="upload"]').click(function(){
alert("click");
});
$('input[id^=“upload”]”)。更改(函数(){
警报(“aa”);
$(本)。在('')之后;
警报($(“#upload_3”).attr(“name”);
});
$('input[id^=“upload”])。单击(函数(){
警报(“点击”);
});
当我单击“上传”元素时,它会触发
单击
和更改
事件,并警告“aa”和“上传3”。然后,它在HTML中的“upload”元素之后添加了
。但是,当我单击新添加的元素(“upload_3”元素)时,单击和更改甚至不会触发。您需要将事件处理程序附加到动态附加的元素。使用jQuery
,.on()
方法将事件处理程序附加到jQuery对象中当前选定的元素集。从jQuery 1.7
开始,.on()
方法提供附加事件处理程序所需的所有功能
这可能会帮助您:
$(document).on('click','input[id^="upload"]',function(){
alert("click");
});
另外,还可以查看。事件在加载DOM(静态元素)时绑定到元素。在动态添加某些元素时,您需要自己附加事件
下面的代码将使用将单击事件绑定到动态添加的元素
$(this).after(“”).bind('click',function(){
警报(“为新元素触发的单击事件”);
});
您也可以使用这个方法。从jQuery 1.7开始,.on()方法提供附加事件处理程序所需的所有功能
发件人:
事件处理程序仅绑定到当前选定的元素;他们
在代码调用.on()时页上必须存在。
如果新的HTML被注入到页面中,请选择元素和
将新HTML放入页面后附加事件处理程序
$(this).after(“”).on('click',function(){
警报(“为新元素触发的单击事件”);
});
在这种情况下,您需要设置委托事件处理程序;这可以通过以下方式实现:
在这种情况下,#parent
节点指的是
元素最近的父元素。单击事件首先由该父节点处理,然后在调用单击处理程序之前进行转换,以确保该
引用了正确的节点。对于动态添加到DOM中的元素,可以使用“on”或“live”。但“开”是首选
$('input[id^="upload"]').change(function(){
var _this = $(this)
$('<input type="file" name="upload_3" id="upload_3"/>').insertAfter(_this);
});
$(document).on('click','input[id^="upload"]',function(){
// do your stuff
});
$('input[id^=“upload”])。更改(函数(){
var\u this=$(this)
$('')。后面插入(_this);
});
$(文档)。在('click','input[id^=“upload”]”上,函数(){
//做你的事
});
thaks非常喜欢,但没有按预期工作,TypeError:jQuery(…)。on不是函数,请帮助我,thanks@user2245634你可以发布你的脚本的样子吗。谢谢,但是当我在('click',function()…)上使用时;显示错误“$(…)。on不是函数”,绑定时无效('单击',函数()…);工作顺利。
$(this).after('<input type="file" name="upload_3" id="upload_3"/>').on('click', function(){
alert('Click event fired for the new element');
});
$('#parent').on('click', 'input[id^="upload"]', function() {
// do your stuff here
});
$('input[id^="upload"]').change(function(){
var _this = $(this)
$('<input type="file" name="upload_3" id="upload_3"/>').insertAfter(_this);
});
$(document).on('click','input[id^="upload"]',function(){
// do your stuff
});