【问题标题】:Does jQuery have any function to determine the tag type of the DOM element(s) referenced by jQuery object?jQuery 是否有任何函数来确定 jQuery 对象引用的 DOM 元素的标签类型?
【发布时间】:2011-07-04 01:24:36
【问题描述】:

jQuery 是否有任何函数来确定 jQuery 对象引用的 DOM 元素的标签类型?我正在编写一个 jQuery 插件和...

jQuery.fn.myPlugin() {
    return this.each(function() {
       var $this = $(this);
       // <---------------------------------------HERE!
    });
}

我想知道this&lt;input&gt;元素还是&lt;div&gt;元素,不直接使用DOM。

【问题讨论】:

    标签: jquery dom


    【解决方案1】:

    这样做:

    this.nodeName;
    

    ...或者为了安全起见,将其转换为特定情况:

    this.nodeName.toLowerCase();
    

    nodeName 属性是widely supported 的属性,在元素节点的情况下(如您的情况)将为您提供标签名称。

    【讨论】:

    • 为什么nodeNametagName更好的链接。
    • @Box9:我打算将来自 quirksmode 的关于tagName 的注释粘贴到答案中,但我想我会顺其自然。但是,是的,nodeName 是要走的路。 :o)
    【解决方案2】:

    为什么不直接使用 DOM?既然您在this 中已经有一个方便的DOM 对象,我会说只是使用它。如果你只有有你可以做的jQuery对象:

    $this.attr("tagName") == "DIV"
    

    $this.is("div")
    

    但没有必要。

    【讨论】:

    • 我会说能够通过attr 访问tagName 是jQuery 消除属性和属性之间区别的副作用,不应依赖。
    【解决方案3】:

    你可以使用tagName:

    this.tagName; //notice this is the DOM element not the jQuery object.
    

    http://reference.sitepoint.com/javascript/Element/tagName

    【讨论】:

      【解决方案4】:

      应用prop("tagName")方法获取html元素的标记名,例如:

      $this.prop("tagName");
      

      【讨论】:

        猜你喜欢
        • 2011-01-14
        • 2011-10-21
        • 2011-04-08
        • 2011-03-01
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多