【问题标题】:How to get table row index when the column textbox value change using jQuery使用jQuery更改列文本框值时如何获取表行索引
【发布时间】:2015-06-16 16:02:59
【问题描述】:

我想在表格价格文本框值发生变化时获取行索引和文本框值。目前我得到了一些未定义的值。

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;

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要将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();
            //....
        });
    });
    

    【讨论】:

      【解决方案2】:

      将函数中的oTextBox替换为$(oTextBox),然后就可以用html()代替innerHTML了,像这样

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

      【讨论】:

        猜你喜欢
        • 2013-05-10
        • 2013-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多