Jquery - 获取具有相同类的多个跨度的文本? [英] Jquery - Get the text of multiple spans with the same class?
问题描述
我对jquery比较新,所以我希望这是一个简单的问题。
我需要将多个跨度附加到无序列表中的行项目。
基本上,每个行项目都包含一个,我需要抓取该跨度的内容并将其附加到底部它包含的订单项。这是我到目前为止所拥有的:
I'm relatively new to jquery, so I have what I hope will be a simple question.
I need to append multiple spans to the line items in an unordered list.
Essentially, each line item contains a and I need to grab the content of that span and append it to the bottom of the line item it's contained in. Here's what I have so far:
我的jquery代码:
$("ul").ready(function(){
var Name = $(".name") .text();
var Content = $(".content") .text();
$("li") .append("<span class=\"additional\"><a href=\"/addinfo.php\">"+ Name +"'s additional info</a></span>");
});
需要修改的原始HTML:
<ul>
<li>
<span class="name">John Doe</span><br />
<span class="content">John is an excellent Swimmer</span><br />
</li>
<li>
<span class="name">Jane Doe</span><br />
<span class="content">Jane loves to play basketball</span><br />
</li>
</ul>
这是我得到的输出:
-
John Doe
John是一位出色的游泳选手
John DoeJane Doe的附加信息
John Doe
John is an excellent Swimmer
John DoeJane Doe's additional info
Jane Doe
Jane喜欢打篮球
John DoeJane Doe的附加信息
Jane Doe
Jane loves to play basketball
John DoeJane Doe'sadditional info
这是理想的结果:
-
John Doe
John是一位出色的游泳选手
John Doe的额外信息
John Doe
John is an excellent Swimmer
John Doe's additional info
Jane Doe
Jane喜欢打篮球
Jane Doe的其他信息
Jane Doe
Jane loves to play basketball
Jane Doe's additional info
正如您所看到的,不是仅使用所有名称变量并将它们放在一起,而不是仅仅使用该行项目的名称变量。
我确定它需要某种类型的这个,$(this)或.each调用它,但我似乎无法在任何地方的文档中找到它。
As you can see, instead of taking the all the "Name" var's and putting them together, instead of just using the "Name" var of that line item. I'm sure it needs some type of this, $(this), or .each call on it, but I can't seem to find this in the documentation anywhere.
有人可以帮忙吗?
谢谢!
特洛伊
Can someone help? Thanks! Troy
推荐答案
试试这个
$("ul > li").each(function() {
var Name = $(".name", this) .text();
var Content = $(".content", this) .text();
$(this).append("<span class=\"additional\"><a href=\"/addinfo.php\">"+ Name +"'s additional info</a></span>");
});
这将循环遍历UL列表中的每个LI并将它们视为单独的实体。你有两个主要问题。一个是你没有限制你的jQuery选择的上下文,所以你得到两个.name类并将它们组合在一起,这就是为什么你有两个名字。然后你将值添加到所有LI对象。
This will loop through each LI in the UL list and treat them as individual entities. You had two major problems. One is that you were not limiting the context of your jQuery selection so you were getting both ".name" classes and combining them together, that is why you got both names. And then you were adding the values to all LI objects.
这篇关于Jquery - 获取具有相同类的多个跨度的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!