【问题标题】:Accessing and using Light-DOM content from a polymer-element definition从聚合物元素定义中访问和使用 Light-DOM 内容
【发布时间】:2014-04-28 23:41:30
【问题描述】:

这里有个问题。我有一个非常简单的polymer-element,它在其中包含一系列<a> 锚标签(Light-DOM),它创建了某种导航栏。因此,我的简单解决方案包括访问 Light-DOM(从聚合物元素)以了解用户在其中放置了多少个锚点,并获得一些我需要在模板中生成事物的信息,如下所示:

<!-- this is the polymer-element -->
<polymer-element name='x-nav' >
  <template>

    <style>
      a {color: blue;}
      li{display: inline-block;}
    </style>

    <nav>
      <ul>
        <template repeat="{{links}}">
          <li>
            <a href="{{href}}">{{innerHTML}}</a>
          </li>
        </template>
      </ul>
    </nav>
  </template>

  <script>
    Polymer('x-nav', {
      ready: function(){
        this.links = [];

        for(var i = 0; i < this.children.length; i++){
          this.links.push(this.children[i]);
        }
      }
    });
  </script>
</polymer-element>

<!-- this is the implementation in the Light-DOM  -->
<x-nav>
  <a href='/hone'>home</a>
  <a href='/about'>about</a>
  <a href='/contact'>contact</a>
</x-nav>

问题是,当我们想要创建可自定义的元素并且我们不知道什么或如何做时,我真的不知道这是否是一个好方法,或者是否有更好的方法或“最佳实践”来完成这类事情用户将在 light-dom 端放置许多标签。谢谢! :D

【问题讨论】:

    标签: polymer


    【解决方案1】:

    这对我来说似乎相当合理,应该可以正常工作,只要 &lt;x-nav&gt; 的链接是静态的。

    需要注意两点,而不是 this.children,您可以尝试 this.querySelectorAll('a') 以确保您只获得“a”节点。

    您也可以考虑使用 &lt;content select='a'&gt;&lt;/content&gt;,因为它可以响应 x-nav 的 light dom 的变化,但我不知道有什么方法可以将每个锚点放在单独的 &lt;li&gt;&lt;content&gt; 中。 &lt;content select='a[nth-child({{idx}})]'&gt;&lt;/content&gt; 可能会起作用,要求您只跟踪 light dom 中有多少个锚点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多