簡體   English   中英

使用jQuery更改列文本框值時如何獲取表行索引

[英]How to get table row index when the column textbox value change using jQuery

價格表文本框值更改時,我想獲取行索引和文本框值。 目前,我正在獲得一些未定義的值。

的HTML

<table class="table table-striped">
    <thead>
        <tr>                   
            <th>Product</th>                              
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <input type="text" class="form-control product">
            </td> 
            <td>
                <input type="text" oninput="javascript:GetValue(this);" class="form-control price">
            </td>
        </tr>
    </tbody> 
</table>

的JavaScript

function GetValue(oTextBox) {
    var price = oTextBox.value;
    var product = oTextBox.parent().prev().innerHTML.value;
    var rowindex = oTextBox.closest('tr').index();
}

我收到此錯誤:

TypeError:oTextBox.parent不是函數var product = oTextBox.parent()。prev()。innerHTML.value;

用$(oTextBox)替換函數中的oTextBox,然后可以使用html()代替innerHTML,如下所示

$(oTextBox).parent().prev().html()

您需要在$中包裝oTextBox才能使用jQuery方法。 這是因為oTextBox ...或... this是一個DOM元素,而不是jQuery對象。 從而:

var product = oTextBox.parent().prev().innerHTML.value;

應該:

var product = $(oTextBox).parent().prev().find('input').val();

和:

var rowindex = oTextBox.closest('tr').index();

應該:

var rowindex = $(oTextBox).closest('tr').index();

建議

我鼓勵您不要使用內聯JS:

<input type="text" class="form-control price">

然后您的jQuery將是:

$(function() {
    $('input.price').on('input', function() {
        var price = this.value;
        var product = $(this).parent().prev().find('input').val();
        var rowindex = $(this).closest('tr').index();
        //....
    });
});

暫無
暫無

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

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