【问题标题】:What is the difference between the selectors #id and [id$='id']?选择器#id 和 [id$='id'] 有什么区别?
【发布时间】:2014-10-06 10:03:09
【问题描述】:

两种说法有什么区别:

 $("span[id$='id']").text(var);
  // And
 $("#id").text(var);

HTML 代码为:<span class="normal11" id="id"></span>

【问题讨论】:

  • 第一个是以选择器结尾的属性,第二个是id选择器。就是这样.. :\
  • 问题标题和问题正文不同... :-?
  • 不知道为什么人们不赞成这个问题,因为 ID 选择器使用更快的 JavaScript 函数 document.getElementById()。

标签: javascript jquery html


【解决方案1】:

第一个使用 ends with 选择器,而第二个使用普通的 id 选择器。

Attribute Ends With Selector [name$="value"]

ID Selector ("#id")

【讨论】:

    【解决方案2】:

    通过 JQuery 上的文档:

    $("#id") 使用 JavaScript 函数 document.getElementById(),效率极高。 Link.

    所以,第二种方式应该更快,应该使用。

    【讨论】:

      【解决方案3】:

      id选择器和属性选择器的一些区别是

      由于 id 选择器称为 document.getElementById(), 它只返回第一个 id 等于的元素。

      但是,如果你使用属性选择器,它将返回所有 id 属性等于该属性的元素。

      但重复的 id 在 HTML 中实际上是无效的,永远不应该使用。

      如果您真的想这样做,请改用 class。

      例子

      $("#id-selector").click(function(){
          $("#test").css("color", "red");
      });
      $("#attr-selector").click(function(){
          $("*[id=test]").css("color", "blue");
      });
      

      http://jsfiddle.net/toucyqas/1/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 2015-10-14
        • 1970-01-01
        • 2012-10-06
        • 2010-10-07
        • 1970-01-01
        相关资源
        最近更新 更多