jquery判断是否有某个属性---某个属性是否存在
获取一个元素的属性,如果存在某个属性会返回属性的值,如果不存在则会返回"undefined",如图:
我在chrome下做测试,判断属性是否存在可用
var attr = $(selector).attr('name'); if ( attr == undefined) { alert(111); }
但是有网友说这样更好一些:
var attr = $(selector).attr('name'); // For some browsers, `attr` is undefined; for others, `attr` is false. Check for both. if (typeof attr !== typeof undefined && attr !== false) { // Element has this attribute }
为了适配更多的应用场景,大家可用第二种方法,否则第一种即可。
更多前端教程知识,请查阅 HTML中文网 !!