如何在JavaScript中访问自定义HTML属性? [英] How do I access custom html attributes in javascript?
问题描述
我只提供有用的资源来解决问题。
<!DOCTYPE html>
< html>
< body id =owner_profile>
< script>
document.write(您有:);
document.write(document.getElementById('buy')。token);
< / script>
< / body>
< / html>
我希望它显示令牌,但它给出的是未定义的
结果为:
华友世纪
您有:undefined
属性和属性之间有区别。要获取属性,请使用 getAttribute(token)
。
许多(预定义的)属性映射到属性(或者相反,我不知道)。例如,如果你设置了一个单元格的 colSpan
属性,你也会影响它的 colspan
属性。
然而有时候两者是完全不同的。最值得注意的是,如果您在该框中输入内容,则输入的值
属性不会更改。但是值
属性会。这意味着您可以使用 elem.value = elem.getAttribute(value)
来重置文本框。
作为一般规则,您应该总是使用 get / setAttribute
来更改元素属性,因为您无法依赖该属性。
注意:这些属性应该是数据:
< a id = buydata-owner =789data-token =1000data-wrapper =purchasename =oname>
Hi im facing problem in this html document please help me
Im very new to this.
May be i am fool to missing something out.
I have put only useful source here to solve please.
<!DOCTYPE html>
<html>
<body id="owner_profile">
<a id="buy" owner="789" token="1000" wrapper="purchase" name="oname">Hurray!</a><br>
<script>
document.write("You Have: ");
document.write(document.getElementById('buy').token);
</script>
</body>
</html>
I want it to display token but its giving undefined
Result is :
Hurray!
You Have: undefined
There is a difference between attributes and properties. To get the attribute, use getAttribute("token")
.
Many (predefined) attributes are mapped to properties (or the other way around, I don't know). So for example if you set a cell's colSpan
property, you will also affect its colspan
attribute.
However sometimes the two are very different. Most notably, the value
attribute of an input will NOT change if you type in the box. However the value
property will. This means that you can always reset a textbox with elem.value = elem.getAttribute("value")
.
As a general rule, you should always use get/setAttribute
to change an elements attributes, because you can't rely on the property being there.
Side-note: Those "attributes" should be data:
<a id="buy" data-owner="789" data-token="1000" data-wrapper="purchase" name="oname">
这篇关于如何在JavaScript中访问自定义HTML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!