Javascript 从 jQuery() 获取子元素的 .text()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4968458/
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
getting .text() of children elements from jQuery()
提问by OpenCode
I'm having trouble to get the proper formatted texts of each child elements, either as an Array or in as text.
我无法获得每个子元素的正确格式化文本,无论是作为数组还是作为文本。
I had tried
我试过了
var name= jQuery(".childOne").text(); var number = jQuery(".childTwo").text();
var name= jQuery(".childOne").text(); var number = jQuery(".childTwo").text();
but it joins all the name/number text in name and number.
但它加入了名称和号码中的所有名称/号码文本。
HTML is:
HTML是:
<span class="parent"><span class="childOne">David</span><span class="childTwo">541</span></span>
<span class="parent"><span class="childOne">Gruce</span><span class="childTwo">162</span></span>
<span class="parent"><span class="childOne">Proman</span><span class="childTwo">743</span></span>
and I need to generate output in multi-dim-array so that each child-element's-text can be figured out properly.
我需要在多维度数组中生成输出,以便可以正确计算出每个子元素的文本。
Preferred output can be in array or in any form.
首选输出可以是数组或任何形式。
Array
(
0 = > array (
0 => "David",
1 => "541"
),
1 = > array (
0 => "Gruce",
1 => "162"
),
2 = > array (
0 => "Proman",
1 => "743"
)
)
采纳答案by BaggersIO
try this:
尝试这个:
var data = [];
$('span.parent').each(function() {
var $this = $(this);
data.push({
'name' : $this.find('span.childOne').text(),
'number' : $this.find('span.childTwo').text()
});
});
BTW: jQuery uses the Sizzle selctor engine. You should define the element type before the class, like span.parent
. This is much more faster.
顺便说一句:jQuery 使用 Sizzle 选择器引擎。您应该在类之前定义元素类型,例如span.parent
. 这要快得多。
回答by Felix Kling
If this is a fixed structure, you can do:
如果这是一个固定结构,你可以这样做:
var data = [];
$('.parent').each(function() {
data.push({
'name': $(this).children('.childOne').text(),
'number': $(this).children('.childTwo').text()
});
});
Edit: Obviously forgot .text()
;)
编辑:显然忘记了.text()
;)
回答by Kimtho6
回答by Krabats
@Dyvor
@Dyvor
BTW: jQuery uses the Sizzle selctor engine. You should define the element type before the class, like span.parent. This is much more faster.
顺便说一句:jQuery 使用 Sizzle 选择器引擎。你应该在类之前定义元素类型,比如span.parent。这要快得多。
Not true! Check this performance test. It is actually the other way around.
不对!检查此性能测试。它实际上是相反的。
http://jsperf.com/jquery-class-selector-vs-type-class-selector
http://jsperf.com/jquery-class-selector-vs-type-class-selector
回答by alexl
$('.parent').each(function(index) {
alert($(this).find('.childOne').text());
alert($(this).find('.childTwo').text());
});
After you can put them into an array
在您可以将它们放入数组之后