Javascript jQuery-在粘贴事件后获取元素的ID
粘贴文本后,我想获取目标div的ID。之后动态生成div,代码不起作用: HTMLJavascript jQuery-在粘贴事件后获取元素的ID,javascript,jquery,html,Javascript,Jquery,Html,粘贴文本后,我想获取目标div的ID。之后动态生成div,代码不起作用: HTML 尝试使用父类。wrap粘贴到div $('.wrap div.entry').on("paste", function(){ console.log("current box ID: " + $(this).attr("id") ); }); 如果动态创建.entry,则可以使用 您正在将事件绑定到wrap div,因此这就是在回调中的含义 将事件绑定更改为: $('.wrap .entry')
尝试使用父类
。wrap
粘贴到div
$('.wrap div.entry').on("paste", function(){
console.log("current box ID: " + $(this).attr("id") );
});
如果动态创建.entry
,则可以使用
您正在将事件绑定到wrap div,因此这就是
在回调中的含义
将事件绑定更改为:
$('.wrap .entry').on("paste", function(){
console.log("current box ID: " + $(this).attr("id") );
});
您需要查看事件的目标(事件发生的地方),然后找到包装该事件的.entry
。如果您想支持在.entry
元素中有任何复杂的结构,就不必直接查看目标
$('.wrap').on('paste', function(event){
console.log('paste id: ' + $(event.target).closest('.entry').attr('id'));
});
不确定为什么要针对“容器”附加事件。我相信你有两个选择
$('.wrap').on("paste", function(e){
console.log("current box ID: " + e.target.id );
});
或
我会选择第二个选项,因为将事件直接附加到相关元素上比将事件直接附加到容器上更为清晰,并使用e.target
方法
$('.entry').on("paste", function(e){
console.log("current box ID: " + this.id ); // this.id is all you need to get any current id
});
因为您在wrap类上绑定了“粘贴”事件(该类没有属性id),所以会得到NULL
必须将其绑定到具有id属性的输入字段
$('.wrap .entry').on("paste", function(){
console.log("current box ID: " + $(this).attr("id") );
});
但是如果.entry是动态创建的?
$('.wrap').on("paste", function(e){
console.log("current box ID: " + e.target.id );
});
$('.entry').on("paste", function(e){
console.log("current box ID: " + this.id );
});
$('.entry').on("paste", function(e){
console.log("current box ID: " + this.id ); // this.id is all you need to get any current id
});
$('.wrap .entry').on("paste", function(){
console.log("current box ID: " + $(this).attr("id") );
});