简体   繁体   中英

How to select all items in a list using jQuery Selector

I am creating a dynamic list on these lines:

<li class="MainMenuList" data-role=list-divider>
    <li data-icon=check id="1">
        <a name="n1" id="id-1">Text-1</a>
    </li>
    <li data-icon=check id="2">
        <a name="n2" id="id-2">Text-1</a>
    </li>
    <li data-icon=check id="3">
        <a name="n3" id="id-3">Text-1</a>
    </li>
</li>

How can I run JQuery .each() selector to access all the value in the list. Trying this doesn't produce ant result.

$( ".MainMenuList li a" ).each(function( index ) {
    var n1 = $(this).attr('name');
    var n2 = parseInt ($(this).attr('id'));
    alert( index + "-" + n1 + "-" + n2);
});

Your HTML is invalid, the outside li should be a ul for it to be valid.

<ul class="MainMenuList" data-role=list-divider>
    <li data-icon=check id="1">
        <a name="n1" id="id-1">Text-1</a>
    </li>
    <li data-icon=check id="2">
        <a name="n2" id="id-2">Text-1</a>
    </li>
    <li data-icon=check id="3">
        <a name="n3" id="id-3">Text-1</a>
    </li>
</ul>

This line

var n2 = parseInt ($(this).attr('id'));

is the same as

var n2 = parseInt("id-2");

and parseInt will not return the 2, it will return NaN.

You would have to use a regular expression

$(this).attr('id').match(/\d+/)[0]

or split to pull out the number

$(this).attr('id').split("-")[1]

or you could just reference the parents id if that is a valid assumption.

$(this).parent().attr('id')

You're calling parseInt() on a string. If you know your IDs will always be in the form id-N you could just do

var id = $(this).attr("id");
var n2 = parseInt(id.split("-")[1]);

Here's a jsFiddle of your code

  • As mentioned in the comments, your first <li> element should be a <ul>
  • You should also either change the <a> id to strictly a number (since your parsing it as an integer) or just retrieve the number part (via substr or something else)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM