Jquery捕获特定div之外的链接

时间:2022-06-16 18:30:07

I need to catch the event when a user clicks a hyperlink outside of a specific div element. To demonstrate :

当用户单击特定div元素之外的超链接时,我需要捕获该事件。展示 :

If I have this HTML :

如果我有这个HTML:

<a id = "1" href="/someurl..">link</a>
<a id = "2" href="/someurl..">link</a>
<a id = "3" href="/someurl..">link</a>

<div id="content">
   <a id = "4" href="/someurl..">link</a>
</div>

I need to catch the event where the user clicks every hyperlink outside of the div with id of "content". But ignore the event when the links inside the div "content" is clicked.

我需要捕获用户单击id为“content”的div之外的每个超链接的事件。但是当点击div“content”中的链接时忽略该事件。

------------------UPDATE----------------

Someone suggested I include what i'm trying to achieve to add clarity. And what the best way to do this is the question.

有人建议我包括我想要达到的目的,以增加清晰度。最好的方法是问题。

My use case is that, I have a div where some operations (links) such as sort, edit etc is being utilized. While links outside are links that redirects to other pages. I want to make a confirm modal using bootbox if a user navigates away. I could use the unload but it also fires when I click on the edit,sort operations (links inside the div).

我的用例是,我有一个div,其中正在使用一些操作(链接),如排序,编辑等。外部链接是重定向到其他页面的链接。如果用户导航,我想使用bootbox进行确认模式。我可以使用卸载但是当我点击编辑,排序操作(div中的链接)时它也会触发。

Thanks!

4 个解决方案

#1


You can use jQuery's siblings() method to target specifically the siblings of your div element:

您可以使用jQuery的siblings()方法专门针对div元素的兄弟节点:

.siblings( [selector ] )

.siblings([selector])

Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

获取匹配元素集中每个元素的兄弟元素,可选择通过选择器进行过滤。

$('#content').siblings('a').on('click', function() { ... });

#2


you can use the .not() operator or :not.

你可以使用.not()运算符或:not。

$('a').not('#content a').click(function(){
    //...do something
})

#3


use :not()

$('a:not(#content a)')

DEMO

#4


There are many ways. One way

有很多方法。单程

$('a').click(
    function(){
        if($(this).closest('#content')){
            return;
    }
});

closest checks if there is a parent element with id content.

最近检查是否存在具有id内容的父元素。

#1


You can use jQuery's siblings() method to target specifically the siblings of your div element:

您可以使用jQuery的siblings()方法专门针对div元素的兄弟节点:

.siblings( [selector ] )

.siblings([selector])

Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

获取匹配元素集中每个元素的兄弟元素,可选择通过选择器进行过滤。

$('#content').siblings('a').on('click', function() { ... });

#2


you can use the .not() operator or :not.

你可以使用.not()运算符或:not。

$('a').not('#content a').click(function(){
    //...do something
})

#3


use :not()

$('a:not(#content a)')

DEMO

#4


There are many ways. One way

有很多方法。单程

$('a').click(
    function(){
        if($(this).closest('#content')){
            return;
    }
});

closest checks if there is a parent element with id content.

最近检查是否存在具有id内容的父元素。