2016-04-29 56 views
0

How to get the id of the element clicked using jQuery這個問題的答案是獲得點擊元素的id。如何獲取點擊區域的ID,但不是父級ID?

但它給出了所有的ID。

例如

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

當點擊DIV two我想要得到的id僅一two。但是下面的腳本也會給出父母身份。

$("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 
}); 

是否有任何inbuild方法來做到這一點。 JS Fiddle

回答

3

您需要event propagation停止父到子元素:

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

Working Demo

0

這不是太難。觀看此視頻:

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

使用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>

1

在不改變目標元素。

事件對象可用於實現此目的。 $(event.target)將給當前目標元素 使用event.stopPropagation()停止單擊內部div時事件的傳播(bubbling)。否則,你會看到內&外層div的兩個警報

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

    }); 

入住這jsfiddle