gpt4 book ai didi

javascript - 如何实现jQuery的.not()?

转载 作者:行者123 更新时间:2023-11-28 14:03:50 27 4
gpt4 key购买 nike

我有这样的代码:

document.onmousedown = function(){
alert('test');
}

现在,除了 ID 为“box”的元素外,单击都应该调用此函数,即相当于 jQuery 的 .not() 选择器。

jQuery 代码为:

$(document).not('#box').mousedown(function(){
alert('test');
});

如何在不使用 jQuery 的情况下实现同样的效果?

编辑:我不需要 jQuery 代码,但我想要一个类似于 Javascript 中 jQuery 的 .not() 选择器的操作。

编辑:我正在制作一个类似 addthis 的小部件。这是一个 10kb 的文件,当选择文本时会显示一个弹出窗口。它不会使用 jQuery。

就我而言,当选择文本时,会显示一个弹出窗口。当单击小部件以外的文档时,小部件应该消失。

最佳答案

要正确执行此操作,您需要检查e.target || 是否有效。 e.srcElement 或其任何父级具有 id === 'box'

例如:(使用 jQuery)

$(document).mousedown(function(e) {
if ($(e.target).closest('#box').length)
return;

//Do things
});

没有 jQuery:

function isBox(elem) {
return elem != null && (elem.id === 'box' || isBox(elem.parentNode));
}
document.onmousedown = function(e) {
e = e || window.event;
if (isBox(e.target || e.srcElement))
return;
//Do things
};

或者,您可以处理 box 元素的 mousedown 事件并取消冒泡。

关于javascript - 如何实现jQuery的.not()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3239698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com