如何防止 jquery 全局选择器选择 Polymer 元素之外的东西

How to prevent jquery global selector selects something outside of the Polymer element

我正在尝试在我的 Polymer 元素 <my-element> 中使用基于 jquery 的库。但是,一旦一页中有多个这样的 <my-element>,图书馆只会 select 第一个,因为它 selecting 一个 id 在一个实例中是唯一的<my-element> 个,但重复了多个。如何给 jquery select 或一个域,以便它只会 select 在其中?

它不起作用,因为 jQuery's id selector 已优化为仅获取第一个:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.


你可以传递jQuery selector's context作为它的第二个参数(有趣的是,如果你传递多个上下文,它会选择多个id):

// Initialize selected domains
$('#init-id', '.first-domain, .second-domain').initializeLibrary();

// Initialize all id in DOM
$('#init-id', '*').initializeLibrary();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first-domain">
  <img id="init-id" />
</div>
<div class="second-domain">
  <img id="init-id" />
</div>
<div class="do-not-initialize-domain">
  <img id="init-id" />
</div>


或者,您的组件可以使用 Polymer.dom(this.root):

进行自我初始化
<dom-module id="my-component">

  <template>
    My component - yay!
  </template>

  <script>

    Polymer({

      is: 'my-component',

      ready: function() {
        $(Polymer.dom(this.root)).initializeLibrary();
      }

    });

  </script>

</dom-module>