簡體   English   中英

jquery:在可點擊的div中保持<a>鏈接可點擊

[英]jquery: keep <a> link clickable in clickable div

我想要做的是阻止點擊div,如果用戶點擊該div內的鏈接。 但是沒有使用.click(function(){}); 在鏈接上。

這是代碼:

$('div.feature').click(function() { window.location = $(this).attr('rel');});

這是div的示例內容:

<div id="feature" rel="urlnumberone">
some text
<a href="javascript:topicchange(this);" class="insideLink">Link</a>
</div>

由於某些特定原因, 我不能使用這樣的東西

$('.insideLink').click(function(event){
    event.stopImmediatePropagation();
});

我必須使用這個“topicchange()”函數,有什么方法可以阻止事件傳播?

謝謝!

您提供的示例應該有效,但您的div的ID為“feature”,但在js中您定位的是一個類。 jsfiddle.net/SNP3K

<div id="feature" rel="urlnumberone">
    some text
    <a href="#" class="insideLink">Link</a>
</div>

$('div#feature').click(function() { 
    alert('div');
});

$('.insideLink').click(function(event){
    event.stopImmediatePropagation();
    alert('link')
});
<div id="feature" onclick="location.href='index.php';">
   <a href="anotherpage.php">link</a>
</div>

很容易!

根據http://api.jquery.com/bind/,event.stopPropagation應該允許執行目標上的其他事件處理程序。 您仍然可以從Href執行,但您也可以通過忽略它來處理默認的點擊冒泡到div。

完整演示: http//jsfiddle.net/leomwa/qrFQM/

片段:

function topicChange()
{
    alert('Message from Link: After the div mouse event, I can execute');
    return false;
}

$('div#feature').click(function(evnt)
{
    var $originatingTarget = $(evnt.target);
    if ($originatingTarget && $originatingTarget.is('.insideLink'))
    {
        alert('Message from Div: Ahh! You clicked on Link...');
        evnt.stopPropagation(); // Allows other handlers on the event.target to be executed.
    }
});

和@shanethehat非常相似。

感謝@shanethehat要求澄清。

$(document).ready(function() {
    $('div#feature').click(function() {
        alert('div');
    });
    $('div#feature a').click(function(evt) {
        evt.stopPropagation();
    });
});

function topicchange(targ) {
    alert('link');
    return false;
}

這是允許的嗎? 主題更改函數直接從href調用,但阻止click事件傳播。 或者一切都發生在topicchange中?

暫無
暫無

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

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