简体   繁体   English

如何使用 jQuery Selector 选择列表中的所有项目

[英]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.如何运行 JQuery .each() 选择器来访问列表中的所有值。 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.您的 HTML 无效,外部 li 应该是 ul 才有效。

<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.并且 parseInt 不会返回 2,它会返回 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.或者,如果这是一个有效的假设,您可以只引用父母的 id。

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

You're calling parseInt() on a string.您正在对字符串调用parseInt() If you know your IDs will always be in the form id-N you could just do如果您知道您的 ID 将始终采用id-N的形式,您可以这样做

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

Here's a jsFiddle of your code这是你的代码的jsFiddle

  • As mentioned in the comments, your first <li> element should be a <ul>正如评论中提到的,你的第一个<li>元素应该是一个<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)您还应该将<a> id更改为严格的数字(因为您将其解析为整数)或仅检索数字部分(通过substr或其他方式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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