jQuery 的 hasAttr() 等价方法

Avatar of Chris Coyier
Chris Coyier

jQuery 实际上并没有 .hasAttr() 函数。你可能会认为它有,但可惜,它没有。

一个 StackOverflow 线程 提供了一些非常好的解决方案。

获取属性,检查值

var attr = $(this).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
}

原生 JavaScript 有方法

如果你只有 jQuery 引用……

$(this)[0].hasAttribute("name");

jQObject[0].hasAttribute("name");

筛选选择

$(this).is('[name]');

$(this).filter("[name='choice']");