【问题标题】:What is the difference between this and $(this) [duplicate]this 和 $(this) 有什么区别 [重复]
【发布时间】:2011-06-26 13:17:10
【问题描述】:

可能重复:
What's the difference between $(this) and this in jQuery?

jquery selector中,示例代码为:

<body>
  <select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
<script>

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " "; // I interested it this line
              });
          $("div").text(str);
        })
        .trigger('change');
</script>

</body>

在示例代码中,有一段代码:

str += $(this).text() + " ";

我在想,为什么这里不用str += this.text() + " ";?换句话说,为什么不在这部分代码中使用this 而使用$(this)?在这种情况下this$(this) 有什么区别?

【问题讨论】:

标签: jquery jquery-ui jquery-selectors


【解决方案1】:

jQuery 的each 函数将this 设置为每次调用迭代回调(docs) 的raw DOM 元素。在该原始元素上调用 $() 会为您提供一个包裹在其周围的 jQuery 对象,让您可以访问诸如 text 之类的 jQuery 函数。

【讨论】:

    【解决方案2】:

    this 是一个标准的 javascript 对象,$(this) 是 jQuery 包装的对象,暴露了所有 jQuery 的优点,比如常规 JavaScript 所没有的函数和属性。

    有时不需要 jQuery 包装器,这可能被认为是矫枉过正。

    【讨论】:

      【解决方案3】:

      出于同样的原因,您使用$("select") 而不是select。它将对象放入适当的 jQuery 上下文中并返回 jQuery 包装的对象。

      【讨论】:

        【解决方案4】:

        $("this") 是 jquery 而 'this' 是 javascript。

        【讨论】:

          猜你喜欢
          • 2013-08-09
          • 2010-11-06
          • 2011-04-12
          • 2013-05-26
          • 1970-01-01
          • 2011-04-10
          • 2012-10-06
          • 2012-10-31
          相关资源
          最近更新 更多