在tr表Jquery中做foreach

时间:2014-08-13 22:05:38

标签: javascript jquery

我有一个表格HTML。我想获得所有列名称。我没有尝试,但没有。

$('#tblmodelos th').each(function () {
    var $data = $(this).html();
    console.log($data);
});

3 个答案:

答案 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>
相关问题