问题描述
例如,如果我有这个:
<div id="blah" myattribute="something">whatever</div>
我是否可以确保没有浏览器会忽略(从而使旧版 JavaScript 无法访问)myattribute
?我知道这很丑陋且不标准,但非常有用.或者如果他们这样做了,jQuery 仍然能够得到他们吗?
浏览器不会抱怨无法识别的属性,Javascript 和 jQuery 仍然可以访问它们:
console.log( $('#blah').attr('myattribute') );//某物console.log( document.getElementById('blah').getAttribute('myattribute') );//某物
但是,您应该使用 HTML5 data-*
属性,该属性专门用于自定义属性.jQuery 有 data()
方法来访问/设置它们:
whatever<脚本>console.log( $('#blah').data('myattribute') );//某物
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?
Browsers won't complain about unrecognized attributes, and Javascript and jQuery will still be able to access them:
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 the data()
method for accessing/setting them:
<div id="blah" data-myattribute="something">whatever</div>
<script>
console.log( $('#blah').data('myattribute') ); // something
</script>
这篇关于浏览器如何处理 HTML 元素上的无效/未指定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!