gpt4 book ai didi

javascript - Polymer - 动态模板渲染

转载 作者:行者123 更新时间:2023-11-29 22:03:11 25 4
gpt4 key购买 nike

是否有可能在运行时或某些 light-dom 元素可用时动态地在 polymer 元素中呈现模板?我有以下情况:

index.html

<mega-menu>
<span class="menuTriggerText">Open Menu</span>
<ul class="test">
<li>TEST1</li>
<li>TEST2</li>
</ul>
<ul class="test">
<li>TEST1</li>
<li>TEST2</li>
</ul>
</mega-menu>

在我的 polymer-element.html 中,我想做如下事情:

<template>
<template repeat="{{temp}}"><p>I want to try this</template>
</template>

Polymer('mega-menu, {
created:function(){},
ready: function(){
//getting markup from light-dom
this.temp = document.getElementsByClassName('test');
},
attached:function(){},
detached: function(){},
attributeChanged: function(attrName, oldVal, newVal){}
});

现在,我的问题是 - 如何让它发挥作用?我需要在我的模板上绑定(bind)一些东西吗?或者我需要某种事件监听器或观察器吗?

谢谢,Gbeschbacher

最佳答案

这正是content insertion points是给。您可以选择顶级 light DOM 标记以在 Shadow DOM 中的特定位置呈现。 <content select=""></content>采用 CSS 选择器并从轻型 DOM 中获取节点。

你的例子是:

<polymer-element name="mega-menu" noscript>
<template>
<content select=".test"></content>
</template>
</polymer-element>

对于这样一个简单的案例,您不需要像这样深入研究轻型 DOM,但为了完整起见,我们可以让您的示例使用一些重要的调整:

  1. document.getElementsByClassName('test')在整个文档中查找节点。这不是你想要的。你只想要 <mega-menu> 的 child .而不是 document使用 this (例如 this.querySelectorAll('.test') )。
  2. 你给了 <template repeat="{{temp}}">一个节点列表。它将无法消除这一点。它需要一个数组。类似于 this.temp = [].slice.call(this.querySelectorAll('.test'));会工作。

http://jsbin.com/balodowi/2/edit

关于javascript - Polymer - 动态模板渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22458340/

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