从铁表中的元素读取数据属性 [英] Reading data-attribute from element inside iron-list

查看:61
本文介绍了从铁表中的元素读取数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用iron-list这样创建div列表:

I create a list of divs using an iron-list like this:

<iron-list items="[[chats]]" as="item" style="height:500px;">
    <template>
        <div class="item title" data-recipient$="[[item.recipient]]">
            <iron-icon class="big" src="../icons/games.svg"></iron-icon>
        </div>
    </template>
</iron-list>

我有一个Polymer方法,此方法稍后会调用并循环div.title.

I have a Polymer method which is called later-on and loops the div.title.

然后我可以设法设置它们的颜色,但是我无法设法读出数据属性:

I can then manage to set their color, but I can not manage to read out the data-attribute:

var elems = document.querySelectorAll(".title");
[].forEach.call(elems, function(el) {
    el.style.color = "red"; // works
    console.log(el.getAttribute("data-recipient")); // prints out null
});

那是为什么?

推荐答案

如果您在Polymer方法中,请避免使用document.querySelector(),因为它查询整个文档而不是查询元素的本地DOM,并且此函数不会能够查询元素的影子DOM.您应该改用 this.$$('.title') .

If you're inside a Polymer method, avoid using document.querySelector() because it queries the entire document instead of only your element's local DOM, and this function would not be able to query the element's shadow DOM. You should use this.$$('.title') instead.

但是,我无法在 Codepen (即el.dataset.recipientel.getAttribute('data-recipient')都返回期望值).

However, I cannot reproduce the symptom you're seeing in this Codepen (i.e., el.dataset.recipient and el.getAttribute('data-recipient') both return the expected value).

这篇关于从铁表中的元素读取数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆