jQuery选择“集合”中的项目(例如表格中的单元格)

时间:2011-08-16 22:20:50

标签: jquery collections selector

我有一个HTML表格,其中包含我用于批量编辑的输入元素。我在下面构建了一个skelton html示例。有人可以帮我弄清楚如何做以下事情:

  • 为每个“数量”字段添加一个选择器,例如.change()
  • 获取数量和金额字段中的值,例如.VAL()
  • 更新总计字段,例如的.text()

主要的挑战是HTML是由我的ASP.Net MVC应用程序中的View生成的,输入id的命名约定是“objectName_indexNumber_propertName” - 例如MyObject_1_Quantity。

我会做一个for-loop / .each(),然后做一个字符串manimpulation来获取id并做我的魔法吗?有没有更好的办法?感谢。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            // how do I select all of them?
            $('#MyObject_1_Quantity').change(DoCalculation);
        });

        function DoCalculation() {
            alert("what should I do here? I need to know the index/row I'm in, and which cell triggered me.");

        }
    </script>

</head>
<body>

    <p>Test jquery Selector</p>
    <table>
        <tr>
            <td>Row 1</td>
            <td><input type="text" id="MyObject_1_Quantity" /></td>
            <td><input type="text" id="MyObject_1_Rate" /></td>
            <td><span id="MyObject_1_Total">$100.00</span></td>
        </tr>
        <tr>
            <td>Row 2</td>
            <td><input type="text" id="MyObject_2_Quantity" /></td>
            <td><input type="text" id="MyObject_2_Rate" /></td>
            <td><span id="MyObject_2_Total">$100.00</span></td>
        </tr>
        <tr>
            <td>Row 3</td>
            <td><input type="text" id="MyObject_3_Quantity" /></td>
            <td><input type="text" id="MyObject_3_Rate" /></td>
            <td><span id="MyObject_3_Total">$100.00</span></td>
        </tr>            
    </table>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

这会在每行的第二个<td>上放置一个处理程序。然后处理程序中的this将是该输入,因此您可以将嵌套输入和相邻单元格用于计算,并在<span>中设置值。

示例: http://jsfiddle.net/Skjbv/1/

$(document).ready(function() {
    $('table tr td:nth-child(2)').change(DoCalculation);
});

function DoCalculation() {
    var row = this.parentNode;
    input1 = this.firstChild.value;
    input2 = row.cells[2].firstChild.value;
    span =   row.cells[3].firstChild;

     // convert to Number----v----------v
    span.innerHTML = ('$' + (~~input1 * ~~input2).toFixed(2));
     // create string with 2 decimal places-----------^

}

如果它不是那么一致,你可以依赖第二个单元格,那么你可以将DOM选择更改为this,这将处理程序直接放在输入上:

示例: http://jsfiddle.net/Skjbv/3/

$(document).ready(function() {
    $('table tr td input[id$="_Quantity"]').change(DoCalculation);
});

function DoCalculation() {
    var row = $(this).closest('tr');
    input1 = this.value;
    input2 = row.find('input[id$="_Rate"]').val();
    span = row.find('span[id$="_Total"]');

    span.html('$' + (~~input1 * ~~input2).toFixed(2));
}

这些使用attribute-ends-with-selector[docs]来选择ID属性末尾具有适当值的元素。