开发者

Get value of 4 divs by :first, :second, :nth - jQuery

开发者 https://www.devze.com 2023-02-06 17:03 出处:网络
How do I get the value of <div> <span class=\"xxx\" id=\"VariesAlways\">x1</span> <span class=\"xxx\" id=\"VariesAlways\">x2</span>

How do I get the value of

<div>
    <span class="xxx" id="VariesAlways">x1</span>
    <span class="xxx" id="VariesAlways">x2</span>
    <s开发者_如何学运维pan class="xxx" id="VariesAlways">x3</span>
    <span class="xxx" id="VariesAlways">x4</span>
</div>

Normaly

$('.xxx').trigger(function() {

    $(this).attr('value');
});

But I want it as

$('.xxx:first').attr('value');
$('.xxx:second').attr('value');
$('.xxx:third').attr('value');
$('.xxx:fourth').attr('value');

But when an alert($('.xxx:first').attr('value')); is done it gives me undefined.

Thanks Jean


Well, .attr('value') will not work if the element has no attribute value.. Thats for sure :)

To select them by the order you want, you should use either the :eq pseudo selector or, better (=faster) the .eq() method.

$('span.xxx').eq(0).text()
$('span.xxx').eq(1).text()
$('span.xxx').eq(2).text()
$('span.xxx').eq(3).text()

.eq() needs the index as parameter.
Anyway, you also can just loop over them by invoking .each()

$('span.xxx').each(function(index, elem) {
    alert(elem.textContent || elem.text);
});

.each() will loop over the nodes as they appear in the DOM. To its probably the better way to go.

Reference: .eq(), .each()


<span> tags don't have a value attribute. You want to use .text(). or .html()

$('.xxx:first').text();


You could use :nth-child()

$('.xxx:nth-child(i)').text()

where i = {1,2,3,4} (note that the counting starts at 1)


I think you first need to make you id's unique and then something like:

$('.xxx').trigger(function() 
{      
       var content = $(this).text();
}); 

So to expand on your example:

alert($('.xxx:first').text());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号