如何在jQuery中选择单个元素? [英] How do I select a single element in jQuery?

查看:121
本文介绍了如何在jQuery中选择单个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的表结构:

I have a table structure that looks like:

<table>
 <tr id="row1">
   <td>
     <div>row 1 content1</div>
   </td>
   <td>
     <div>row 1 content2</div>
   </td>
   <td>
     <div>row 1 content3</div>
   </td>
 </tr>
 <tr id="row2">
   <td>
     <div>row 2 content1</div>
   </td>
   <td>
     <div>row 2 content2</div>
   </td>
   <td>
     <div>row 2 content3</div>
   </td>
 </tr>
 <tr id="row3">
   <td>
     <div>row 3 content1</div>
   </td>
   <td>
     <div>row 3 content2</div>
   </td>
   <td>
     <div>row 3 content3</div>
   </td>
 </tr>
</table>

使用jQuery,我试图在第三行的第二个单元格中选择DIV.我尝试了以下方法(以及其他方法):

Using jQuery I am trying to select the DIV in the second cell of the third row. I tried the following (amongst other things):

var d = $('#row3').children(':eq(1)').children(':eq(0)');

我得到的是一个带有单个元素的数组(我所追求的DIV),然后我必须使用d [0]进行访问.为什么jQuery为什么返回单个元素数组,我认为使用上面的选择器会直接返回DIV元素?

What I get back is an array with a single element (the DIV I'm after) and I have to then access using d[0]. Why is jQuery returning a single element array, I thought using the selector above would return the DIV element directly?

@ Shog9 -嗯...好吧,我的大脑刚刚开了灯,我现在明白了.干杯.

@Shog9 - Duh...Ok a light just switched on in my brain, I get it now. Cheers.

推荐答案

jQuery始终返回一组元素.有时,集合为空.有时,它仅包含一个元素.这样做的好处是,无论匹配多少个元素,您都可以编写代码以相同的方式工作:

jQuery always returns a set of elements. Sometimes, the set is empty. Sometimes, it contains only one element. The beauty of this is that you can write code to work the same way regardless of how many elements are matched:

$("selector").each(function()
{
   this.style.backgroundColor = "red";
});

好玩!

这篇关于如何在jQuery中选择单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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