欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jQuery 判断是否包含某个属性 JQuery 判断某个属性是否存在 hasAttr 有大用 有大大用

JQuery 判断某个属性是否存在 hasAttr

在JQuery编码中,我们会判断元素是否存在某个属性.比如是否包含 class="new" 的样式呢.JQuery判断就非常简单了,因为有 hasClass这个方法 $("input[name=new]").hasClass("new") 即可判断.

但是有时候我们需要判断别的属性,比如有的 a 链接包含 rel 属性,有的没有rel属性.这时该怎么判断呢?

这时就没有现成的方法了. 如果存在某个属性 $("#aid").attr("rel") 会返回 rel的值,如果不存在 rel属性则会返回"undefined"

undefined 就是 undefined类型 , if($("#aid").attr("rel")=="undefined") 这个判断可能不成立.

因为类型不相同.

建议使用 if(typeof($("#aid").attr("rel"))=="undefined") 即可

  1. $("#aid").is(':rel')

来自  https://blog.csdn.net/huaishuming/article/details/30463419


1、Get the attribute, check the value

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
}

2、Native JavaScript has a way

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

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

3、Filter the selection

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

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


来自  https://www.cnblogs.com/yunspider/p/5084191.html

普通分类: