使用jQuery查找td和div之间的选定值

时间:2015-08-14 16:41:44

标签: javascript jquery html-table

下面的函数用于查找参考编号然后进行比较,然后如果找到相应的值,则根据输入框修改单元格值。这很好用,但是,如何修改下面的现有函数以捕获

之间的值
<td><div>this value here</div></td>

以下是相关的Javascript:

function changeit() {
    var valueToFind = $('#number').val();
    $('#data > tbody> tr').each(function(index) {
        console.log(index);
        var firstTd = $(this).find('td:first');
        if ($(firstTd).text() == valueToFind) {
            console.log("found: " + index + ":" + valueToFind);
            $(this).find('td:eq(1)').text($('#item').val());
            $(this).find('td:eq(2)').text($('#color').val());
        }
    })
}

以下是HTML标记:

<!DOCTYPE html>

<html>

<head>

    <meta http-equiv="Content-Language" content="en-us">

</head>

<body>

    Number:*
    <input type="text" id="number">
    <br> Items:
    <input type="text" id="item">
    <br> Color:
    <input type="text" id="color">
    <br>

    <br>

    <input type="button" onclick="changeit()" value="save">

    <br>

    <table id="data" style="width: 100%" cellspacing="1" class="style1">
        <tr>
            <td>
                <div><b>Number*</b></div>
            </td>
            <td>
                <div><b>items</b></div>
            </td>
            <td>
                <div><b>Colors</b></div>
            </td>
        </tr>
        <tbody>
            <tr>
                <td>
                    <div>
                        <div>123</div>
                    </div>
                </td>
                <td>
                    <div>Boats</div>
                </td>
                <td>
                    <div>red</div>
                </td>
            </tr>
            <tr>
                <td>
                    <div>456</div>
                </td>
                <td>
                    <div>Vehicles</div>
                </td>
                <td>
                    <div>blue</div>
                </td>
            </tr>
            <tr>
                <td>
                    <div>789</div>
                </td>
                <td>
                    <div>Motorcycles</div>
                </td>
                <td>
                    <div>green</div>
                </td>
            </tr>
        </tbody>
    </table>

</body>

</html>

1 个答案:

答案 0 :(得分:0)

更改

 var firstTd = $(this).find('td:first'); 

 var firstTd = $(this).find('td:first div');