浏览器如何处理 HTML 元素上的无效/未指定属性? [英] How browsers handle invalid/unspecified attributes on HTML elements?

查看:37
本文介绍了浏览器如何处理 HTML 元素上的无效/未指定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有这个:

<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 元素上的无效/未指定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆