【问题标题】:How to retrieve values of custom DOM properties?如何检索自定义 DOM 属性的值?
【发布时间】:2015-12-09 18:43:21
【问题描述】:

我正在尝试在下面的 HTML 块中为 itemindex="x 检索 amount="y" 的值,

<ul>
 <li><span class="vaTop" itemindex="14" amount="500.00">$500</li>
 <li><span class="vaTop" itemindex="15" amount="300.00">$300</li>
 <li><span class="vaTop" itemindex="16" amount="150.00">$150</li>
 <li><span class="vaTop" itemindex="17" amount="75.00">$75</li>
 <li><span class="vaTop" itemindex="18" amount="35.00">$35</li>
 </ul>

我不知道如何用通常的方式解决这个问题,document.getElementBy...('').value;

如果有人有任何建议,将不胜感激。

【问题讨论】:

  • 使用elm.getAttribute(strAttrName),或使用document.registerElement创建具有直接属性绑定的自定义标签。

标签: javascript html dom customization


【解决方案1】:

尝试使用document.querySelector(),属性选择器"li span[itemindex='17']",例如选择itemindex属性设置为"17"的元素; Element.getAttribute() ,正如@dandavis 所建议的那样。

var el = document.querySelector("li span[itemindex='17']");
console.log(el.getAttribute("amount"))
<ul>
  <li><span class="vaTop" itemindex="14" amount="500.00">$500</li>
 <li><span class="vaTop" itemindex="15" amount="300.00">$300</li>
 <li><span class="vaTop" itemindex="16" amount="150.00">$150</li>
 <li><span class="vaTop" itemindex="17" amount="75.00">$75</li>
 <li><span class="vaTop" itemindex="18" amount="35.00">$35</li>
 </ul>

另见

What is the point of the "is" syntax when extending elements in web components?

Using data attributes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多