我正在使用 Shadow root 编写一个应用程序,我发现自己使用 shadow.children[i].addEventListener('click', fn);
太多了,所以我尝试创建一个自定义函数来简写它,所以我写道:
var $shadow = function(shadow, el, fn){
console.log(shadow);
console.log(el);
var children = shadow.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
console.log('child '+child.id+', el '+el);
if (child.id === el) {
console.log('match');
return shadow.children[i].addEventListener('click', fn);
break;
}
}
}
并从自定义元素中调用它;
$shadow(shadow, 'd', alert('yap!'));
问题在于,一旦调用元素,函数就会直接执行,而不是等待“监听”指定元素上的“单击”操作。
有想过如何解决吗?
最佳答案
var $shadow = function(shadow, el, fn){
console.log(shadow);
console.log(el);
var children = shadow.children;
console.log(children.length);
for (var i = 0; i < children.length; i++) {
var child = children[i];
console.log(children[i]);
console.log('child '+child.id+', el '+el);
if (child.id === el) {
console.log('match');
return shadow.children[i].addEventListener('click', function(){
console.log(fn);
fn();
});
break;
}
}
}
$shadow(shadow, 'd', function(){alert("yap");});
我知道您想在这个地址进行操作..
[http://jsfiddle.net/p4fcoftL/]
祝你找到工作
关于Javascript 将功能添加到影子根中的自定义元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29031135/