jQuery - 获取粘贴事件后的元素ID

use*_*265 0 html javascript jquery

粘贴文本后,我想获取目标div的ID.之后div会动态生成,代码不起作用:

小提琴

HTML

<div class="wrap">

<div class="entry" id="1" contenteditable="true">paste here</div>
<div class="entry" id="2" contenteditable="true">paste here</div>
<div class="entry" id="3" contenteditable="true">paste here</div>
<div class="entry" id="4" contenteditable="true">paste here</div>

 </div>
Run Code Online (Sandbox Code Playgroud)

JS

$('.wrap').on("paste", function(){

    console.log("current box ID: " + $(this).attr("id") );
});
Run Code Online (Sandbox Code Playgroud)

Dha*_*hak 6

尝试使用父类.wrap您需要使用.entry类,因为您正在粘贴它div

$('.wrap div.entry').on("paste", function(){   
    console.log("current box ID: " + $(this).attr("id") );
});
Run Code Online (Sandbox Code Playgroud)

如果.entry是动态创建的,那么您可以使用事件委派

$(document.body).on('paste','.wrap .entry',function(){
    console.log("current box ID: " + $(this).attr("id") );
});
Run Code Online (Sandbox Code Playgroud)

小提琴