问题
我想使用 javascript 收集所有表格数据,然后发送回应用程序的某些部分。
HTML
<table>
<tbody>
<tr>
<td>
<span>hello</span>
</td>
<td>
<ul>
<li>1<span>:2000</span></li>
<li>2<span>:3000</span></li>
<li>
<span>link</span>
<span>
<a href=''>failed login</a>
</span>
</li>
</ul>
</td>
</tbody>
</table>
output Expected :
hello 1 :2000 :3000 link failed login
提前致谢。
答案 0 :(得分:1)
您可以使用如下的递归函数。没有规范化,您可能希望删除多余的空格并在每个元素的文本之间插入空格。
// Get the text within an element
// Doesn't do any normalising, returns a string
// of text as found.
function getTextRecursive(element) {
var text = [];
var el, els = element.childNodes;
for (var i=0, iLen=els.length; i<iLen; i++) {
el = els[i];
// May need to add other node types here that you don't want the text of
// Exclude script element content
if (el.nodeType == 1 && el.tagName && el.tagName.toLowerCase() != 'script') {
text.push(getTextRecursive(el));
// If working with XML, add nodeType 4 to get text from CDATA nodes
} else if (el.nodeType == 3) {
// Deal with extra whitespace and returns in text here if required
text.push(el.data);
}
}
// Insert a space between each text string and return
// a single string
return text.join(' ');
}
答案 1 :(得分:1)
试试这个
$(document).ready(function() {
var texts = [];
$("table tr td").each(function(i, elem) {
texts.push($.trim($(elem).text()))
});
var str = texts.join(':').replace(/(\r\n|\n|\r)/gm, "")
alert(str);
});
见工作示例: - http://jsfiddle.net/fL28r/84/
thansks