如何在 jQuery.each 循环中获取特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1252249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:00:34  来源:igfitidea点击:

How do I get specific element in jQuery.each loop

jquery

提问by Steven

I need to get the div containing the street address within the list. The div has a class called address ( div class="address" )

我需要获取包含列表中街道地址的 div。div 有一个名为 address 的类( div class="address" )

I cannot use jQuery("#storeList li .address"), because there are other elements I need to acces as well.

我不能使用 jQuery("#storeList li .address"),因为我还需要访问其他元素。

I have the following code:

我有以下代码:

jQuery("#storeList li").each(function() {
  var n = jQuery(this.address).text(); // <- This does not work
  alert(n);
});

How do I access each DIV element of type Address?

如何访问地址类型的每个 DIV 元素?

回答by Scharrels

jQuery("#storeList li").each(function() {
  var n = jQuery(this).find(".address").text(); // <- This works
  alert(n);
});

回答by Raghav

$('#storeList li').each(function() 
{
  var n = $(this).find('div.address').html(); 
  alert(n);
});

回答by Bill Bell

jQuery("#storeList li:has(.address) .address").each(function() {
    alert(this.innerHTML);
});

An alternative that avoids using a second query. As a jQuery newbie I don't know what the tradeoffs really are though.

避免使用第二个查询的替代方法。作为一个 jQuery 新手,我不知道真正的权衡是什么。