javascript - 当列文本框值更改时如何使用 jQuery 获取表行索引

标签 javascript 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 is not a function var product = oTextBox.parent().prev().innerHTML.value;

最佳答案

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

关于javascript - 当列文本框值更改时如何使用 jQuery 获取表行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872709/

相关文章:

javascript - 检查所有玩家是否准备好

javascript - 函数未在 setTimeout 内执行

jquery - 使导航栏具有粘性

javascript - 如何使用 jquery 的 $ajax 调用进行 REST 调用?

jquery - 使用 jQuery touchwipe 默认删除某些删除

javascript - 为什么 javascript 会增加我的号码?

javascript - 纹理加载器不适用于法线贴图

javascript - 基于嵌套函数条件的 'return true' 的最佳方法

javascript - AngularJS 获取外部 JSON 的问题

javascript - 提前输入 : Adding a last option