簡體   English   中英

jQuery-粘貼事件后獲取元素的ID

[英]jQuery - get ID of element after paste event

粘貼文本后,我要獲取目標div的ID。 以后div是動態生成的,代碼不起作用:

js小提琴

的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>

JS

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

    console.log("current box ID: " + $(this).attr("id") );
});

嘗試使用父類.wrap粘貼該div需要使用.entry

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

如果.entry是動態創建的,則可以使用事件委托

$(document.body).on('paste','.wrap .entry',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 );
});

要么

$('.entry').on("paste", function(e){

    console.log("current box ID: " + this.id );
});

我將選擇第二個選項,因為更清楚地將事件直接附加到相關元素上,而不是將事件直接附加到容器上並使用e.target方法。

您將事件綁定到wrap div, this就是在回調中的含義。

將事件綁定更改為:

$('.wrap .entry').on("paste", function(){
    console.log("current box ID: " + $(this).attr("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類上綁定了'paste'事件(沒有屬性ID),所以您將獲得NULL。

您必須將其綁定到具有id屬性的輸入字段中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM