jQuery 从具有相同类的所有元素中获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12031342/
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:12:52  来源:igfitidea点击:

Get the text from all elements with the same class

jquery

提问by Dirty Bird Design

In making a US map that displays store locations using this map plug inI've got it mostly nailed down but want a better way to perform one funciton. I have a list of stores below the map and want to group all stores in the same state and display the store names in a sidebar when you hover over the state. I have the hover and displaying of data working but want to improve. Instead of just writing a function for each state and explicitly stating what to display, I would like to get the first p.cnfrom each div that has the same class.

在使用此地图插件制作显示商店位置的美国地图时,我已经基本确定了它,但想要一种更好的方法来执行一个功能。我在地图下方有一个商店列表,并希望将处于同一州的所有商店分组,并在您将鼠标悬停在该州上时在侧边栏中显示商店名称。我有数据的悬停和显示工作,但想要改进。我不只是为每个状态编写一个函数并明确说明要显示的内容,而是想p.cn从每个具有相同类的 div 中获取第一个。

<div class="texas">
    <p class="cn">Store 1</p>
</div>

<div class="texas">
    <p class="cn">Store 2</p>
</div>

mouseoverState: {
    var texas = $('.texas > p.cn').text();
    $('#mysidebarID').html(texas);
}

This is only displaying the first store "store 1" I cannot get it to grab every p.cnfrom each div.texas and display them with a <br>after each one.

这仅显示第一家商店“商店 1”,我无法p.cn从每个 div.texas 中获取每个商店并在每个商店<br>之后显示它们。

How do I get the html from every element with the same class and combine it into a string with each node separated by a <br>?

如何从具有相同类的每个元素中获取 html 并将其组合成一个字符串,每个节点用 分隔<br>

thank you - let me know if I need to clarify anything.

谢谢 - 如果我需要澄清任何事情,请告诉我。

回答by undefined

You can use the each()method, try the following:

您可以使用该each()方法,请尝试以下操作:

var str = "";

$('.texas > p.cn').each(function(){
  str += $(this).text() + "<br>";
})

$('#mysidebarID').html(str);