我可以给标签添加任意属性吗?比如<input type="text"偏好=“silly" /

can I add an arbitrary attribute to a tag like <input type="text" preference="silly"/> and access it in JS code later

本文关键字:quot type input text silly 偏好 添加 标签 任意 属性 比如      更新时间:2023-09-26

是否有一种方法可以用无关的属性来补充DOM元素,或者标记是通过设计固定为特定属性的?举个例子,这可能吗?

<input id="spec" type="text" preference="silly"/> 
然后用jQuery或DOM请求访问这个元素,比如
if ($("#spec").attr("preference")=="silly") {
     document.write("That input is silly")
}
大卫

添加任意的额外属性,充其量只会使HTML无效,并有可能与将来对语言的更改发生冲突。

HTML 5引入data-*属性用于在DOM中存储任意数据。

jQuery可以通过data()方法访问它们。

<input id="spec" data-preference="silly">
if (jQuery('#spec').data('preference') === 'silly') { ... }

您可以简单地使用data:

<input id="spec" type="text" data-preference="silly"/> 
if ($("#spec").data("preference") == "silly") {
     alert("That input is silly");
}