簡體   English   中英

如何防止嵌套在另一個也使用onclick的元素上的鏈接上的click事件?

[英]How I can prevent the click event on a link which is nested on another element which also use onclick?

我有這個簡單的代碼

<span class="doit"><a class="doit"href="ww.domain.com">text</a></span>

我想點擊類“ do it”觸發一個函數,所以我嘗試了

$(document).on('click', '.doit', function(e) {

    // prevents to handle the click for nested objects again
    e.stopPropagation();

    alert("hello world"); 
});

現在,我<a href的問題是,如果單擊<a href ,來自href的鏈接將打開,而不會觸發on.click函數。

我如何防止觸發鏈接而不是on.click事件?

更新1

我嘗試了一個建議的答案,但失敗,因為href鏈接已經打開。 我必須准備打開鏈接,只有on.click事件應該起作用。

<span class="doit">
 <a class="doit" href="http://www.example.com" target="_blank">webcms von 
  <span class="doit">ABC</span>
  <span class="doit">123</span>
 </a>
</span>
if ($(e.target).is("a")) {     
    e.preventDefault(); // stop the href 
    alert("I WILLL not go to " + e.target.href);
    e.cancelBubble = true; // do not click through
    e.stopPropagation(); // just stop the event or it will trigger again on the span
    return false; 
}

console.log('target:'+e.target);

在控制台中,我讀到:[對象HTMLSpanElement

我必須找到一種方法,該方法可以以各種方式對html標簽進行排序或嵌套。

更新2

if ($(e.target).is("a")) 
{     
      e.preventDefault(); // stop the href  
}
e.cancelBubble=true; // do not click through
e.stopPropagation(); // just stop the event or it will trigger again on the span
alert("hello world");

我看到警報“ hello world”,但此后,該鏈接仍將打開

只是測試

但是,我不建議您對這兩個元素使用相同的類

在這里,您可以單擊鏈接和范圍觸發器的onclick,但不能單擊href

順便說一下,嵌套范圍不是正確的HTML

 $(document).on('click', '.doit', function(e) { if ($(e.target).is("a")) { e.preventDefault(); // stop the href alert("I WILLL not go to " + e.target.href); } e.cancelBubble=true; // do not click through e.stopPropagation(); // just stop the event or it will trigger again on the span alert("hello world"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="doit"> <a class="doit" href="http://www.example.com" target="_blank">webcms von <span class="doit">4U</span> <span class="doit">.tools</span> </a> </span> 

替代

 $(document) .on('click', 'a.doit', function(e) { e.preventDefault(); alert("I WILLL not go to " + e.target.href); }) .on('click', 'span.doit', function(e) { alert("hello world"); e.cancelBubble=true; e.stopPropagation() }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="doit"> <a class="doit" href="http://www.example.com" target="_blank">webcms von <span class="doit">4U</span> <span class="doit">.tools</span> </a> </span> 

暫無
暫無

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

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