使用jQuery获取多个元素的文本 [英] Getting multiple elements' text with Jquery
本文介绍了使用jQuery获取多个元素的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取表单元格的值。
I am trying to get the value of a table cell.
例如
<table id='projects'>
<tr>
<td id='a'>aaaaa</td>
<td id='b'>bbbbb</td>
<td id='c'>ccccc</td>
<td id='d'>eeeee</td>
<td id='e'>ddddd</td>
</tr>
</table>
<a id='test' href='#'>test </a>
我想获取aaaaa,bbbbb,ccccc,eeeee,ddddd并将它们分配给我的数组
I want to get aaaaa,bbbbb,ccccc,eeeee,ddddd and assign them to my array
我相信我可以通过下面的Jquery代码获得价值
I believe I can get the value with my Jquery code below
$(document).ready(function(){
$('#test').click(function(){
var tableVal=new Array();
tableVal['a']=$('#a').text();
tableVal['b']=$('#b').text();
tableVal['c']=$('#c').text();
tableVal['d']=$('#d').text();
tableVal['e']=$('#e').text();
})
});
但是,我认为它不太易于维护,如果我有20个标签,则需要很多代码。我想知道是否可以使用 .each
或任何其他更好的方式对此进行存档。谢谢您的帮助。
However, I think it's not very maintainable and take lots of code if I have 20 tags. I was wondering if I can do it with .each
or any better way to archive this. Thanks for the help.
推荐答案
您可以执行以下操作,
var tableVal= [];
$('#projects tr:eq(0) td').each (function () {
tableVal[this.id] = $(this).text();
});
注意::eq(0)-表示第一行。如果要对所有行都做相应修改,或者让我知道是否需要帮助。
Note: :eq(0) - means 1st row.. Modify accordingly if you want to do for all rows or let me know if you need help with that.
这篇关于使用jQuery获取多个元素的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文