我有一个表,其中包含纯文本、输入文本框、选择和跨度的组合。我需要逐行遍历表格,并提取每个单元格中的值。在我的表中,所有的<tr>都有一个特定的css类。
$(".gridBody").each(function(rowindex){
$(this).find("td").each(function(cellIndex){
var cell = $(this).first()
})在我的调试器中,我可以看到$(this).first()返回的是哪种类型的对象,但是我找不到如何进入它的属性。我曾尝试使用jqueries html解析器将其转换回dom元素,但我得到的不是例如textbox,而是类似于[html inputtextbox]的内容。大多数适用于常规dom元素的方法对我来说都不适用。
如果我使用$(.innerText) span,当单元格的内容是纯文本时,它会返回正确的值,但当它们是一种输入形式或嵌套在span元素中时,就不会返回正确值。我真正希望能够做的是得到一个常规的html dom元素,然后我可以用$.is()检查它的类型,然后从那里改变很多逻辑。
如何将表格单元格中的第一个子元素作为html dom元素,以便可以像其他dom元素一样使用jquery进行操作?
发布于 2016-03-17 08:56:08
var collected = $("#myTable td").find("input, textarea, span").map(function(){
return this.value || this.textContent;
}).get();
console.log( collected ); // an array holding values or texthttp://jsbin.com/zewixe/2/edit?html,css,js,console,output
如果您只想要直接的子项,那么使用正确的>选择器
(">input, >textarea, >span")发布于 2016-03-17 09:05:27
下面是我会怎么做:
<table>
<tr>
<td>
<h1>Some stuff.</h1>
</td>
</tr>
<tr>
<td>
<input type="text" value="1"/>
</td>
<td>
<input type="text" value="2"/>
</td>
</tr>
<tr>
<td>
<input type="text" value="3"/>
</td>
</tr>
<tr>
<td>
<input type="text" value="4"/>
</td>
</tr>
</table>$(function() {
function getFormData(selector){
'use strict';
var formTypes = {
text: 'text',
radio: 'radio',
select: 'select'
},
values = [];
$(selector).children().each(function(idx, childNode) {
if (childNode.getAttribute('type') && formTypes[childNode.getAttribute('type')]) values.push(childNode.value);
});
return values;
}
alert(
getFormData('table tr td.someClass')
);})();
http://codepen.io/nicholasabrams/pen/RaKGjZ
https://stackoverflow.com/questions/36049643
复制相似问题