简体   繁体   English

在ul li中查找所有值

[英]Find All a values in ul li

I'm trying to find the list of inner text values of span in a elements within one ul in a div 我正在尝试在div一个ula元素中查找span的内部文本值的列表

In other words, having the markup: 换句话说,具有标记:

<div id="MyId">
   <ul>
      <li><a href="#"><span>Val1</span></a></li>
      <li><a href="#"><span>Val2</span></a></li>
   </ul>
</div>

I'd like to get the array [Val1, Val2] where the div id is my input. 我想获取数组[Val1,Val2],其中div id是我的输入。 I've written some dirty jQuery code involving the each on ul function but it's more complicated than what it should be. 我已经编写了一些肮脏的jQuery代码,涉及each on ul函数,但它比应该的复杂。

Use .each function 使用.each函数

 $('#MyId ul li a span').each(function(){ alert($(this).html()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="MyId"> <ul> <li><a href="#"><span>Val1</span></a></li> <li><a href="#"><span>Val2</span></a></li> </ul> </div> 

var myArr = [];

$("#MyId span").each(function() {
    myArr.push($(this).html());
});

This would push in your array the values you want. 这将把您想要的值放入数组。

//arr = ["Val1", "Val2"]

Having in mind that .html() would actually take everything html-wise inside your span. 请注意, .html()实际上会将HTML范围内的所有内容都包含在html中。 If you just want the text, then use .text() instead. 如果只需要文本,请改用.text()

Fiddle : https://jsfiddle.net/vdu93x8e/ 小提琴https : //jsfiddle.net/vdu93x8e/

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

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