在JavaScript中排除DOM的sub div
我有两个分区。 < div class =“ card” id =“ openwebsite”>
和sub div < div class =“ card__btn”>
如果有人单击我的根div,将被重定向到 example.com
,当某人单击sub div时,它们将重定向到 example.com
& 示例
,他们在两个新选项卡中重定向两个链接。
我想要,如果有人单击root div,他们应该将其重定向到 example.com
,当某人单击sub div按钮时,他们只能将其重定向到 example.net
not not代码> example.com
如何排除sub div < div class =“ card__btn”>
从javaScript中。
代码 :
const webPage = document.querySelectorAll("#openWebsite");
webPage.forEach((e) => {
e.addEventListener("click", () => {
const site = e.getAttribute("data-site");
window.open(site, "_blank") || window.location.replace(site);
});
});
.card {
background: blue;
height: 100px;
width: 500px;
}
<div class="card" id="openWebsite" data-site="https://example.com">
<div class="card__btn">
<a href="https://example.net">
Visit Site
</a>
</div>
</div>
已经从 jQuery排除了selector ,jquery , https://api.jquery.com/not/ , document.document.document.document.queryselector排除Dom 的一部分/MET_DOCUMEMENT_QUERYSELECTORALL.ASP“ RER =“ Nofollow Noreferrer”> https://www.w3schools.com/jsref/met_document_queryselectorallectorall.asp
document.querySelectorAll("#openWebsite").not(".card__btn");
和
document.querySelectorAll(".card").not(".card__btn");
document.querySelectorAll("#openWebsite:not('.card__btn')");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使您的内部DIV位置绝对,然后它将按照您想要的方式工作。
You need to make you internal div position absolute then it will work the way you want.
那里
您的代码绝对可以,只是您
仅用的代替
您使用的代码,因为您在页面上只有一个ID具有“ openwebsite”的ID,
下面是我相信您可以添加到CSS的建议,以使您的项目更加可见
there
your code is absolutely fine, just that you used
instead of
only, because you only have one id on your page with the id "openWebsite",
below is a suggestion I believe you can add to your css to make your project more visible
事件在DOM上冒泡。单击锚时,它将打开
示例.net
。然后它上升到树,您的事件处理程序被触发,导致
example.com
要打开。要停止此操作,您可以使用”代码> 。这样,事件将不会继续爬上树。
因为Stackoverflow不允许打开新的选项卡,所以我还创建了a fiddle 。
Events bubble up the dom. When you click on the anchor it opens
example.net
.Then it goes up the tree and your event handler is triggered, causing
example.com
to be opened.To stop this you can use
Event.stopPropagation
. That way, the event won't continue going up the tree.Because stackoverflow doesn't allow new tabs to be opened, I have also created a fiddle.