在jQuery中通过ID获取底层DOM元素的最佳方法是什么? [英] What's the best way to get the underlying DOM element by ID in jQuery?

查看:453
本文介绍了在jQuery中通过ID获取底层DOM元素的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来像是一个非常基本的问题.假设我有以下Form元素

This sounds like a really basic question. Let's say I have the following Form element

<select id="mySelect"> 

...

使用jQuery,假设我想通过ID来获取它,这样我就可以直接访问其属性之一,例如selectedIndex.

Using jQuery, let's say I want to get it by ID so I can directly access one of its attributes like selectedIndex.

不认为我可以使用

var selectedIndex = $("#mySelect").selectedIndex;

因为#选择器返回一个元素数组.如果我想实际访问select DOM元素,则必须调用

because the # selector returns an Array of Elements. If I wish to actually access the select DOM element, then I have to call

var selectedIndex = $("#mySelect").get(0).selectedIndex;

对吗?是否有一个选择器可以让我直接进入DOM元素,而不必对get(0)进行额外调用"?

Is this correct? Is there a selector that will let me get directly to the DOM element without having to make an "extra call" to get(0)?

我问是因为我来自原型,在这里我只能说:

I ask because I'm coming from Prototype where I can just say:

var selectedIndex = $('mySelect').selectedIndex;

推荐答案

有许多jQuery方法可以获取<select>的值,这些方法不需要您访问实际的DOM元素.特别是,您只需执行以下操作即可获取当前所选选项的值:

There are jQuery ways to get the value of the <select> that don't require you to access the actual DOM element. In particular, you can simply do this to get the value of the currently selected option:

$('#mySelect').val();

但是,有时候,无论出于何种原因,您都确实想访问特定的DOM属性.

Sometimes, however, you do want to access a particular DOM attribute for whatever reason.

虽然您提供的.get(0)语法正确,但也可以在不调用函数的情况下进行操作:

While the .get(0) syntax you provided is correct, it is also possible without the function call:

$("#mySelect")[0].selectedIndex;

jQuery集合的行为类似于数组对象,并通过它公开实际的DOM元素.

A jQuery collection behaves as an array-like object and exposes the actual DOM elements through it.

这篇关于在jQuery中通过ID获取底层DOM元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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