【问题标题】:jQuery find() returns only the first matched result ?jQuery find() 只返回第一个匹配的结果?
【发布时间】:2012-11-08 06:02:14
【问题描述】:

我在 jQuery 中使用 $.find() 方法,但无法获得与选择器条件匹配的所有结果。

这是我的 HTML

<div class="something">
<label> Hello </label>
<div class="selse">
    <label> Hi </label>
    <label class="imp"> This is </label>
    <label class="imp"> Nooo </label>
</div>
<label class="imp"> Sparta </label>
<label class="imp"> Right ? </label>
</div>

<div class="something">
<label> Hell No </label>
<div class="selse">
    <label> Hi </label>
    <label class="imp"> Cant </label>
</div>
<label class="imp"> touch </label>
<label class="imp"> this </label>
 <label class="imp"> MC  </label>
</div>​

所以当我做下面的 JS 时

$("div.something").each(function(index) {
   alert(index + ': ' + $(this).find("label.imp").html())
    });​

我预计它会给我 2 个警报。一个是 0. This is, Nooo, Sparta, Right ? ,另一个是 1. Cant, touch, this, MC 。但我只有 0. This is1. Cant

我尝试在这样的同一函数中使用数组

$("div.something").each(function(index) {
    var arr=[]
    arr = $(this).find("label.cidForm").html();
    alert(arr);
    });​

不,我会收到带有“未定义”的警报框。在这两种情况下我做错了什么?我只想要一个包含 label.imp 元素内所有值的数组。

这是我提出的一个 JSFiddle。 http://jsfiddle.net/WPeKF/1/

【问题讨论】:

  • 试着描述你想做什么,而不是你做错了什么。
  • 我在帖子末尾提到过。没有包括在主题中。对不起。

标签: javascript jquery html find


【解决方案1】:

.html() 和其他 getter 方法只返回第一个匹配元素的值。考虑到这一点,我认为您可以弄清楚需要进行的逻辑更改。

小提琴:http://jsfiddle.net/WPeKF/2/

代码:

var arr = $("div.something").map(function(){
    return $(this).find("label.imp").map(function(){
        return $(this).html();
    }).get().join("");        
}).get();
console.log(arr);

【讨论】:

  • 哦。我只专注于 find() 方法。感谢您的信息。
  • 嵌套映射的唯一目的是将每个东西 div 中的 div 字符串连接成一个字符串。作为比较,jsfiddle.net/WPeKF/3
【解决方案2】:

这应该可以解决问题:

var myArray = $("div.something label.imp").map(function(index) {
    return $(this).html();
});​

【讨论】:

  • 将任何.imp 插入到单个数组中。但是您需要有一个父数组,它存储每个 .something.imp 的数组)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
相关资源
最近更新 更多