为什么使用jQuery(selector).get(0)而不是jQuery(selector)[0]来获取DOM元素? [英] Why use jQuery(selector).get(0) instead of jQuery(selector)[0] to get DOM element?

查看:122
本文介绍了为什么使用jQuery(selector).get(0)而不是jQuery(selector)[0]来获取DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery对 $(选择器).get(0)超过 $(选择器)[0] 如果我只是想把jQuery数组中的第一项作为DOM元素?

Using jQuery is there any benefit to using $(selector).get(0) over $(selector)[0] if I just want to get the first item in the jQuery array as a DOM element?

HTML:

<form id="myForm"></form>

Javascript:

Javascript:

var selector = '#myForm';
var domElement = $(selector).get(0); //Returns [object HTMLFormElement]

//Or
var domElement = $(selector)[0]; //Also returns [object HTMLFormElement]




  • .get()是要键入的更多字符。

  • 如果 $(选择器)为空(未定义

  • .get() 上的jQuery文档指出,您可以简单地使用索引访问器来获取第n个元素,但是您没有获得其他好处 .get(),例如使用负数来从数组末尾返回项目。

  • 此外,您可以调用 .get()没有参数返回jQuery数组的所有DOM元素。

    • .get() is more characters to type.
    • Both methods return the same result if the $(selector) is empty (undefined)
    • The jQuery documentation on .get() notes that you can simply use the index accessor to get the nth element, but you don't get the other benefits of .get() such as using a negative number to return items from the end of the array.
    • Also, you can call .get() with no arguments to return all the DOM elements of the jQuery array.
    • 推荐答案

      .get 允许您使用负指数。例如:

      .get allows you to use negative indices. For example:

      <span>1</span>
      <span>2</span>
      <span>3</span>
      

      $(span)。get(-1); 指的是第三个 span

      但是如果你不需要那个功能而只是想要选择一个元素 .get(0) [0] 是相同的。注意 this [num]

      But if you don't need that feature and only want to select one element .get(0) and [0] are the same. Notice the this[num]:

      // jQuery code
      get: function (num) {
          return num == null ?
      
          // Return a 'clean' array
          this.toArray() :
      
          // Return just the object
          (num < 0 ? this[this.length + num] : this[num]);
      },
      

      这篇关于为什么使用jQuery(selector).get(0)而不是jQuery(selector)[0]来获取DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆