当有人点击非链接时显示警告



这就是我想做的。

向点击页面任何部分(非链接)的用户显示警告

我尝试了这个,但是当链接被点击时警报也出现了。

$('body').click(function(){
alert('Nothing to click here!');
});

我需要从函数中排除链接,但我不知道如何。

你可以试试jQuery:not() selector

$('body:not(a)').click(function(){
alert('Nothing to click here!');
});

本例中可以使用isSameNode()contains()函数

$("body").click(function(event){
if(
document.getElementById("foo").isSameNode(event.target) 
|| document.getElementById("foo").contains(event.target)
){
alert('Click event triggered from inside of <a> element');
return;
}
alert('Click event triggered from outside of <a> element');
});
body {
width:100px;
height:100px;
border: 1px solid black;
}
#foo {
background-color:red;
}
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<body>
<a id="foo">Hello World!!</a>
</body>

最新更新