假设父节点如下:-
<poly-parent>它的子节点为::<poly-child>
我希望父级跟踪一个特定属性的最大值,一个子属性可以具有“attChild”。我能够对元素使用attChildChanged跟踪更改。
家长如何跟踪max attChild?:--
<poly-parent>
<poly-child attChild="2"></poly-child>
<poly-child attChild="4"></poly-child>
</poly-parent>有聚合物(Ic)做这件事的方法吗?我想避免从attChildChanged调用父方法
发布于 2015-02-23 09:06:36
在attChildChanged方法中,您可以这样做:
var max = 0;
for(var i=0; i<document.getElementsByTagName('poly-child').length; i++){
if(parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild")) > max){
max = parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild"));
}
}
return max;假设这个脚本的作用域为<poly-parent>,那么文档将是它的影子DOM的根,并且它将能够访问元素。如果试图在阴影DOM之外运行JS,而<poly-child>元素位于影子DOM中,则必须使用.shadowRoot属性穿透阴影DOM。
编辑
在<poly-parent>中使用变异观察者可以做到这一点
//The max value
var max = 0;
// select the target nodes
var targets = document.getElementsByTagName('poly-child');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//Check the new max
max = 0;
for(var i=0; i<document.getElementsByTagName('poly-child').length; i++){
if(parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild")) > max){
max = parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild"));
}
}
});
});
// configuration of the observer:
var config = { attributes: true };
// pass in the target nodes, as well as the observer options
for(var i=0; i<targets.length; i++){
observer.observe(targets[i], config);
}https://stackoverflow.com/questions/28667904
复制相似问题