javascript - onclick用法 - onclick jquery
如何防止單擊兒童錨時觸發父母的onclick事件? (10)
事件冒泡到已經附加點擊事件的DOM中的最高點。 因此,在您的示例中,即使您在div中沒有任何其他可顯式單擊的元素,div的每個子元素都會將其單擊事件向上鼓起,直到DIV的click事件處理程序捕獲它為止。
有兩種解決方案是檢查誰確實發起了事件。 jQuery隨同事件一起傳遞一個eventargs對象:
$("#clickable").click(function(e) {
var senderElement = e.target;
// check if sender is the DIV element e.g.
// if($(e.target).is("div")) {
window.location = url;
return true;
});
您還可以將一個單擊事件處理程序附加到您的鏈接,以指示它們在自己的處理程序執行後停止事件冒泡 :
$("#clickable a").click(function(e) {
//do something
e.stopPropagation();
})
我目前使用jQuery來使div可點擊,在這個div中我也有錨。 我遇到的問題是,當我點擊一個錨點時,兩個點擊事件都會觸發(對於div和錨點)。 如何防止單擊錨點時觸發div的onclick事件?
這是破碎的代碼:
JavaScript的
var url = $("#clickable a").attr("href");
$("#clickable").click(function() {
window.location = url;
return true;
})
HTML
<div id="clickable">
<!-- Other content. -->
<a href="http://foo.com">I don't want #clickable to handle this click event.</a>
</div>
你也可以試試這個
$("#clickable").click(function(event) {
var senderElementName = event.target.tagName.toLowerCase();
if(senderElementName === 'div')
{
// do something here
}
else
{
//do something with <a> tag
}
});
使用stopPropagation方法,看一個例子:
$("#clickable a").click(function(e) {
e.stopPropagation();
});
正如jQuery Docs所說:
stopPropagation
方法可防止事件冒泡DOM樹,從而阻止任何父處理程序被通知事件。
請記住,它不會阻止其他偵聽器處理此事件 (例如,按鈕的多個單擊處理程序),如果它不是所需的效果,則必須使用stopImmediatePropagation
。
使用return false;
或e.stopPropogation();
將不允許進一步的代碼執行。 它會在這一點停止流動。
如果在可點擊的div中有多個元素,則應該這樣做:
$('#clickable *').click(function(e){ e.stopPropagation(); });
如果您不打算在任何情況下與內部元素進行交互,那麼CSS解決方案可能對您有用。
只需將內部元素設置為pointer-events: none
在你的情況下:
.clickable > a {
pointer-events: none;
}
或者通常針對所有內部元素:
.clickable * {
pointer-events: none;
}
這個簡單的黑客為我節省了大量的時間,同時使用ReactJS進行開發
瀏覽器支持可以在這裡找到: http://caniuse.com/#feat=pointer-events : http://caniuse.com/#feat=pointer-events
所有的解決方案都是複雜的,並且是jscript。 這是最簡單的版本:
var IsChildWindow=false;
function ParentClick()
{
if(IsChildWindow==true)
{
IsChildWindow==false;
return;
}
//do ur work here
}
function ChildClick()
{
IsChildWindow=true;
//Do ur work here
}
添加a
如下:
<a href="http://foo.com" onclick="return false;">....</a>
或return false;
從#clickable
點擊處理程序,如:
$("#clickable").click(function() {
var url = $("#clickable a").attr("href");
window.location = url;
return false;
});
這裡是一個使用Angular 2+的例子
例如,如果你想關閉一個模態組件,如果用戶點擊它:
// Close the modal if the document is clicked.
@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
this.closeModal();
}
// Don't close the modal if the modal itself is clicked.
@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.stopPropagation();
}
<a onclick="return false;" href="http://foo.com">I want to ignore my parent's onclick event.</a>