[英]Get text from all spans in div using jQuery
I'm dynamically adding span elements to a div. 我正在动态地将span元素添加到div中。 I want to retrieve the text from all the span elements in the div at a later stage.
我想稍后再从div中的所有span元素中检索文本。 How do I do this?
我该怎么做呢? I'd like to use jQuery, but Javascript is fine I guess.
我想使用jQuery,但是我猜Javascript很好。
Section of Javascript creating the span elements: 创建span元素的Javascript部分:
var x = ui.item.value;
var span = document.createElement("span");
span.innerHTML=" "+x+"";
$("#selected").append(span);
This is inside an on click event. 这在点击事件中。 The div is called "selected".
div称为“选定”。
You can try something like this: 您可以尝试如下操作:
var txt= ""; $("#selected span").each(function(){ txt += $(this).text();//here you get the values from each span inside selected element }); $("body").append(txt);//here append the collected text inside eg body
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="selected"> <span>1</span> <span>1</span> <span>1</span> <span>1</span> </div>
No need for a .each()
or any other loop. 不需要
.each()
或任何其他循环。 Just calling .text()
will be enough since, according to the JQuery docs , it: 只需调用
.text()
就足够了,因为根据JQuery文档 ,它:
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
获取匹配元素集合中每个元素的组合文本内容(包括它们的后代),或设置匹配元素的文本内容。
So: 所以:
$("#selected").click(function() { var text = $(this).find("span").text(); alert(text); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div id="selected"> <span>1</span> <span>2</span> <span>3</span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.