jquery - 查找具有指定类的每个 div

标签 jquery html css

var data='<div class="shout_msg">
    <span class="username">3</span>
    <span class="message">hello</span>
</div>
<div class="shout_msg">
    <span class="username">0</span>
    <span class="message">yo</span>
</div>
<div class="shout_msg">
    <span class="username">0</span>
    <span class="message">hey</span>
</div>
<div class="shout_msg">
    <span class="username">0</span>
    <span class="message">haha</span>
</div>';

$(data).find(".shout_msg").each(function(index){ 
    console.log($(this).find("span.username").text() ); 
});

它不返回任何东西。基本上,此处显示在变量中的数据来自 AJAX 请求。但无论如何,我犯了一个愚蠢的错误或其他事情。请指正。

最佳答案

在这种情况下,您可能希望使用 filter,因为您不是在对象内部进行搜索。

$(data).filter(".shout_msg").each(function(index){ 
  console.log( $(this).find("span.username").text() );
});

这里有一个快速演示。

http://jsbin.com/ocefeq/1/edit

关于jquery - 查找具有指定类的每个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983249/

相关文章:

jquery - 一个 jQuery 语句中的多个类或 ID 用于寻址一个特定元素

javascript - 当用户滚动 jquery 时更改图像 src 值

javascript - 我正在尝试将选择选项值与常数相乘

javascript - 如何使用JavaScript模板?

javascript - 使用 jquerymobile 滚动标题文本

javascript - 使用 jQuery 删除第二个表单元素而不丢失子元素

html - CSS中h1下的双下划线

javascript - 如何使动画关闭与打开相同

css - Puppeteer - 无法在酒店网站中拉出正确的 CSS 选择器

CSS 定位不适用于 Chrome