簡體   English   中英

查找表標題單元格值(第一列)

[英]Find table header cell value (First Column)

我有一個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());
});

使用$('th:first')

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

這是演示

對於您的代碼:改為使用eq

var selectedElements = $("tr").find("th:eq(0)");

要回答問題1,您的代碼將嘗試查找索引大於0的元素,因此將查找第二個元素。 嘗試刪除gt 這將找到索引小於1的元素,因此它將匹配索引為0的元素。

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

但是,還有其他答案中提到的更好的方法。

嘗試這個

HTML代碼

<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'});                 
});

演示

使用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());


});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM