jquery tagName 用 prop() 方法比较好!
在一些情况下,我们需要在jquery中判断元素的标签名称,以此来确定是否要对该元素进行动作,这是我们会用到prop()。例如,我们判断<img>的父元素是否为<a>,以此来确定是否要为<img>增加链接地址。
通过网上很多资料,我大概总结了四种方法获取元素的名称:
1.get(0).tagName
例如:
$(this).parent().get(0).tagName
2.[0].tagName
例如:
$(this).parent()[0].tagName
3.attr('tagName')
例如:
$(this).parent().attr('tagName')
4.prop('tagName')
例如:
$(this).parent().prop('tagName')
在上面四种方法中,prop()的方法是已经确定可以使用的方法,而attr()的方法似乎并不可用,我尝试通过该方法获取,结果失败。在新版本的jquery中,prop()区别于attr(),具体可以参考这篇文章,阅读jquery官方API了解prop()。
ATTRIBUTE/PROPERTY .ATTR()
.PROP()
accesskey ✓ align ✓ async ✓ ✓ autofocus ✓ ✓ checked ✓ ✓ class ✓ contenteditable ✓ defaultValue ✓ draggable ✓ href ✓ id ✓ label ✓ location * ✓ ✓ multiple ✓ ✓ nodeName ✓ nodeType ✓ readOnly ✓ ✓ rel ✓ selected ✓ ✓ selectedIndex ✓ src ✓ style ✓ tabindex ✓ tagName ✓ title ✓ type ✓ width ** ✓