我是JavaScript新手,这个问题可能看起来很傻。
我有这样的函数:
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('mySelectOptions');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
另一个几乎相同的函数是这样的:
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('newSelectOptions');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
唯一的区别是id,我的问题是如何将两个id添加到同一个函数中?
可能是这样的:
for id in ['mySelectOptions','newSelectOptions']:
document.addEventListener('mouseup', function(e) {
var container = document.getElementById(id);
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
您可以对.querySelectorAll
执行此操作,以选择具有不同id的所有匹配元素。这些id可以用,
分配器(#newSelectOptions,#mySelectOptions
)来写。
document.addEventListener('mouseup', function(e) {
var containers = document.querySelectorAll('#newSelectOptions,#mySelectOptions');
[...containers].forEach(function(container) {
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
});
可以创建一个函数来包装DOM函数代码
function hideContainer(containerId) {
var container = document.getElementById(containerId);
if (!container.contains(e.target)) {
container.style.display = 'none';
}
}
document.addEventListener('mouseup', function(e) {
hideContainer('mySelectOptions');
});
document.addEventListener('mouseup', function(e) {
hideContainer('newSelectOptions');
});
如果您不想使用classes
,您可以创建一个array
的id。
let elemntsIds= ['mySelectOptions', 'newSelectOptions'];
elemntsIds.forEach(function(id) {
document.addEventListener('mouseup', function(e) {
var container = document.getElementById(id);
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
});
请记住,我使用let
在function handler
之外定义数组由于它是block-scoped
,因此您需要在函数处理程序体中将其声明为var,以便它可以是hoisted
,并避免每次事件时都创建新实例。触发