4

我有一个在http://jsfiddle.net/Lijo/sP7zD/中列出的 HTML 表。我需要读取第一列标题的值。我正在使用“gt”和“lt”运算符来做这件事。但它没有获得第一列的值。

  1. 在我编写的脚本中需要对 jQuery 代码进行哪些更改?
  2. 读取第一列标题值的更好方法是什么?

代码

<input type="submit" value="Alert" class="alertButton"/>


<table class="resultGridTable" cellspacing="0" id="detailContentPlaceholder_grdLocalTaxReport"
style="border-collapse: collapse;">
<tr>
    <th scope="col">
        IsSummaryRow
    </th>
    <th scope="col">
        Associate
    </th>
    <th scope="col">
        Gross Amount
    </th>
    <th scope="col">
        Federal Withholding
    </th>


</tr>
<tr>
    <td>
        False
    </td>
    <td>
        Norman Tylor
    </td>
    <td>
        3450
    </td>
    <td>
        32
    </td>
</tr>
</table>

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script>

脚本

$('.alertButton').click(function() {                                                  
    var selectedElements = $("tr").find("th:gt(0):lt(1)");
    $(selectedElements).css('background-color','yellow');
    alert(selectedElements.html());
});

​</p>

4

4 回答 4

3

利用$('th:first')

var selectedElements = $("th:first");

这是演示

对于您的代码:改为使用eq

var selectedElements = $("tr").find("th:eq(0)");
于 2012-09-19T08:12:02.820 回答
1

尝试这个

代码

<input type="submit" value="Alert" class="alertButton" />
<table class="resultGridTable" cellspacing="0" id="detailContentPlaceholder_grdLocalTaxReport"
style="border-collapse: collapse;">
    <tr>
        <th scope="col">
            IsSummaryRow
        </th>
        <th scope="col">
            Associate
        </th>
        <th scope="col">
            Gross Amount
        </th>
        <th scope="col">
            Federal Withholding
        </th>
    </tr>
    <tr>
        <td>
            False
        </td>
        <td>
            Norman Tylor
        </td>
        <td>
            3450
        </td>
        <td>
            32
        </td>
    </tr>
</table>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js">
</script>

JS代码

$('.alertButton').click(function()
    {                                                 
        var selectedElements = $('th').first();
            alert(selectedElements .text());
        selectedElements.css({'background':'yellow'});                 
});

演示

于 2012-09-19T08:49:48.130 回答
1

要回答问题 1,您的代码会尝试查找索引大于 0 的元素,因此它会找到第二个。尝试删除gt. 这将找到索引小于 1 的元素,因此它将匹配索引为 0 的元素。

var selectedElements = $("tr").find("th:lt(1)");

但正如其他答案中提到的,有更好的方法来做到这一点。

于 2012-09-19T08:15:49.217 回答
0

利用var selectedElements = $(".resultGridTable").find("tr:first").find('th:first');

$('.alertButton').click(function()
{

var selectedElements = $(".resultGridTable").find("tr:first").find('th:first');
    $(selectedElements).css('background-color','yellow');
    alert(selectedElements.html());


});

​</p>

于 2012-09-19T08:13:21.013 回答