我有一个表格HTML。我想获得所有列名称。我没有尝试,但没有。
$('#tblmodelos th').each(function () { var $data = $(this).html(); console.log($data); });
答案 0 :(得分:3)
如果您想获得name
属性...
试试这个:
$('#tblmodelos th').each(function () {
var $data = $(this).attr("name");
alert($data);
});
<强> JSFiddle Demo 强>
.html()
会为您提供<th>
和</th>
例如,如果你有:
<th>Testing</th>
它将返回Testing
。
<强>更新强>
使用document.ready
函数,以便在加载DOM后立即执行所有操作。
$(document).ready(function() {
$('#tblmodelos th').each(function () {
var $data = $(this).text();
console.log($data);
});
});
答案 1 :(得分:0)
它可能只是一个好的旧$(document).ready(function() {});
陷阱吗?
$(function() { // same as document.ready
$('#tblmodelos th').each(function () {
var $data = $(this).html();
console.log($data);
});
});
由于您的代码运行正常,如此处http://jsfiddle.net/o6a2vwg0/
否则,如果HTML正确,我认为没有理由为什么这段代码会失败
答案 2 :(得分:0)
如果你的意思是name
列名,那么试试这个
$(function () {
$('#tblmodelos th').each(function () {
var thname = $(this).text();
});
});
工作演示:http://jsfiddle.net/doniyor/45xhw94h/
在这种情况下,您应该使用text()
而不是html()
,因为html()
会检索th
内的所有内容,如果您有类似的内容:
<th>
<span>The column name</span>
</th>
输出html()
将是:
<span>The column name</span>