浏览器如何处理HTML元素上的无效/未指定的属性?
For examlpe, if I have this:
例如,如果我有:
<div id="blah" myattribute="something">whatever</div>
Can I be safe that no browsers will ignore (and thus render inaccessible from legacy JavaScript) the myattribute
? I am aware that this is ugly and not standard, but is quite useful. Or if they do, would jQuery still be able to get them?
我是否可以安全,因为没有浏览器会忽略(从而无法从遗留JavaScript中访问)myattribute?我知道这很难看,也不标准,但是很有用。或者如果他们这么做了,jQuery还能得到它们吗?
4 个解决方案
#1
3
Browsers won't complain about unrecognized attributes, and Javascript and jQuery will still be able to access them:
浏览器不会抱怨无法识别的属性,Javascript和jQuery仍然可以访问它们:
console.log( $('#blah').attr('myattribute') ); // something
console.log( document.getElementById('blah').getAttribute('myattribute') ); // something
However you should use the HTML5 data-*
attribute which is specifically for the purpose of custom attributes. jQuery has has the data()
method for accessing/setting them:
但是,您应该使用HTML5 data-*属性,它是专门用于定制属性的。jQuery有数据()方法来访问/设置它们:
<div id="blah" data-myattribute="something">whatever</div>
<script>
console.log( $('#blah').data('myattribute') ); // something
</script>
更多相关文章
- HTML5 数据集属性dataset
- Javascript学习:案例7--对象属性和方法的遍历、删除、添加.html
- javascript 构造函数中的属性与原型上属性优先级的比较
- 在jQuery中使用css transform属性
- javascript的offset、client、scroll使用方法,相关属性解释原理
- 如何将javascript set style属性返回到CSS默认值
- 对象的属性也要加引号吗
- javascript中的属性类型
- JQuery纯前端导入Excel文件,兼容IE10及IE9版本以下浏览器处理方法