[英]Prevent redirect when clicking on anchors child element
我有一個位於錨點中的按鈕,該按鈕具有一些通過clicking
它來觸發的邏輯。
問題是,每當我單擊該按鈕時,應用程序都會由於anchor
父元素而被重定向。
<a href="foo" id="bar">
<span id="button">click me</span>
</a>
我嘗試像這篇文章中提到的那樣使用.stopPropagation() ,但是它不起作用。
我試過了:
$('#button').on('click', function(e) {
e.stopPropagation();
})
但是,如果我用div
替換父anchor
,那么它就可以工作 - JSFiddle
難道我做錯了什么?
更新:我知道我可以使用e.preventDefault()
阻止重定向,但是,我希望當我單擊父元素時進行重定向,以及當我單擊按鈕時不進行重定向並開始執行我的 JS 函數(打開模式)。
嘗試這個:
$('#bar').on('click', function(e) { if( $(e.target).is('#button') ) { e.preventDefault(); //your logic for the button comes here } //Everything else within the ancho will cause redirection*** });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="foo" id="bar">OK <span id="button">click me</span> </a>
你應該使用e.preventDefault();
在鏈接上:
$('#bar').on('click', function(e) {
e.preventDefault();
});
你也可以在你的例子中一起添加它:
$('#button').on('click', function(e) {
e.stopPropagation();
e.preventDefault();
});
嘗試使用e.preventDefault()
代替:
$('#button').on('click', function (e) {
e.preventDefault();
});
請參閱此解釋 ,了解e.stopPropagation()
無效的原因。
使用return false
:
$('#button').on('click', function (e) {
//some logic
$(this).css('color', 'red');
return false;
});
stopPropagation不起作用的原因是因為它會阻止事件處理程序運行,而不是本機行為。
我知道這個問題已經有了答案,但是,我通過returning false on the "onclick" attribute of the child element
完成我的工作。
<a href="https://google.com">
<button onclick="return doTask()">Do not navigate</button>
</a>
function doTask(){
//... write action
return false; <- This prevents the click action from bubbling up to parent tag
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.