jQuery遍历div并获取其span详细信息 [英] jquery to traverse the div and get its span details

查看:581
本文介绍了jQuery遍历div并获取其span详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的html页面:

I have a html page as below:

<div id="test1">
    <table>
        <tr>
            <td><span id="234">ABKO</span></td>
        </tr>
        <tr>
            <td><span id="1234">ABKO2</span></td>
        </tr>
        <tr>
            <td><span id="2634">ABKO3</span></td>
        </tr>
    </table>    
</div>
<div id="test2">
    <table>
        <tr>
            <td><span id="233">ABKOw</span></td>
        </tr>
        <tr>
            <td><span id="1236">ABKOc</span></td>
        </tr>
        <tr>
            <td><span id="2635">ABKOv</span></td>
        </tr>
    </table>    
</div>

如何获取使用jQuery之间的所有跨度详细信息? 例如,如果我首先考虑div = test1,那么我希望所有soan及其ID和文本 作为 div-> test1 跨度=> id 233&&阿博 跨度=> id 1234&& ABKO2 跨度=> id 22634&& ABKO3

How can i get all the span details between using jQuery? eg if i consider first div=test1 then i want all the soan with their ID and text as div -> test1 Span => id 233 && ABKO Span => id 1234 && ABKO2 Span => id 22634 && ABKO3

推荐答案

您可以像这样遍历所有<span>元素:

You can iterate through all the <span> elements like so:

$('div span').each(function(){
    var $span = $(this);

    var divId = $span.closest('div').attr('id');
    var spanId = $span.attr('id');
    var spanTxt = $span.text()

    // do something with the above
});

您可以在此处看到它.

这是在构建嵌套在div中的span元素列表( CSS选择器 div span).然后,它使用 .each()方法对此列表进行迭代.

What this is doing is building a list of span elements that are nested in a div (CSS selector div span). It then iterates over this list using the .each() method.

在每次迭代中,$(this)均指匹配的span元素.我们在$span变量中捕获了一个引用,因此我们不会继续创建相同的jQuery对象.

Within each iteration $(this) refers to the matched span element. We capture a reference in the $span variable so we don't keep recreating the same jQuery object.

然后,我们使用 .closest()方法来查找与给定选择器(div).这就是我们的父级div.

We then use the .closest() method to find the span's first ancestor that matches the given selector (div). This gets our parent div.

最后 .attr()

Finally .attr() and .text() gets the ID attribute and text values .

这篇关于jQuery遍历div并获取其span详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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