簡體   English   中英

如何獲取點擊區域的ID,而不是父ID?

[英]How to get the id of clicked area but not the parent id?

如何獲得使用jQuery單擊的元素的ID,這個問題的答案是獲得單擊元素的ID。

但是它給出了所有ID。

例如

  <div id="major">
    <div id="two">  </div>
  </div>

當單擊div two我只想獲得一個id ,即為two 但是以下腳本也將提供父ID。

    $("body").on('click','div',function() 
    {   
        alert(this.id);
    });    //It alerts the two and major. But i want two only.

為此,我嘗試放置一些未聲明的函數,以提供預期的結果。 例如

$("body").on('click','div',function() 
{   
    alert(this.id);
    mkh(); #undeclared function
});   

有任何內置方法可以做到嗎? JS小提琴

您需要停止將父事件傳播到子元素:

$("body").on('click','div',function(e){   
  e.stopPropagation();
  alert(this.id);
  mkh(); #undeclared function
});   

工作演示

使用event.target對象。

 $("body").on('click', 'div', function(e) { alert(e.target.id); e.stopPropagation(); }); 
 #two { width: 100px; height: 100px; background: blue; } #major { width: 500px; height: 500px; background: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="major"> <div id="two"></div> </div> 

不更改目標元素。

事件對象可以用於服務目的。 $(event.target)將給當前目標元素使用event.stopPropagation()來在您單擊內部div時停止事件的傳播( bubbling )。 否則,您將看到內部和外部div的兩個警報

    $("body").on('click','div',function(event) 
    {   event.stopPropagation();
   var _getId = $(event.target).attr('id');
    alert(_getId);

    });   

檢查這個jsfiddle

這不太難。 看這個:

$("body").on('click','#two',function() 
    {   
        alert(this.id);
    });

暫無
暫無

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

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