2015-03-13 112 views
0

我使用的阴影根写一个应用程序,我发现使用shadow.children[i].addEventListener('click', fn);我自己这么多,定制元素,因此我试图创建一个自定义函数来速记,所以我写了:的Javascript功能添加在阴影根

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!')); 

问题是直接执行一次的元素被调用,而不是等待“听”到指定元素上的“点击”动作的功能。

任何想法如何解决它?

回答

0
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");}); 

你想在这个ADRESS做我明白..

[http://jsfiddle.net/p4fcoftL/] 

我希望你找到工作

+0

感谢,所以它的工作通过添加 “功能(){}” 时我称呼它,赞赏。 – 2015-03-13 13:26:33