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

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

问题描述

对于考试,如果我有这个:

For examlpe, if I have this:

<div id="blah" myattribute="something">whatever</div>

我是否可以确保没有浏览器会忽略(从而使旧版JavaScript无法访问) myattribute ?我知道这很丑陋而且不标准,但非常有用。或者,如果他们这样做,jQuery仍然可以得到它们吗?

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并且jQuery仍然可以访问它们:

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

但是你应该使用HTML5 数据 - * 属性,专门用于自定义属性。 jQuery有 data() 访问/设置它们的方法:

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:

<div id="blah" data-myattribute="something">whatever</div>

<script>
console.log( $('#blah').data('myattribute') ); // something
</script>

这篇关于浏览器如何处理HTML元素上的无效/未指定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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