-1

这是我的 HTML:

<table id="ParamTbl">
<tbody>
    <tr id="ParamRow">
        <td><label for="paramname[]">Name: </label><input type="text" name="paramname[]" class="paramname"></td>
        <td><label for="paramval[]">Value: </label><input type="text" name="paramval[]"></td>
        <td><label for="paramtype[]">Type: </label><select name="paramtype[]">
                <option selected="true">String</option>
                <option>Double</option>
                <option>Object</option>
            </select></td>
        <td><div id="clrList">X</div></td>
        <td><div id="addrow">Add Param</div></td>
    </tr>
</tbody>
</table>

这是我的 jQuery:

function addParam(ParamName){
    $('#ParamTbl').css('background-color','yellow');
    var clone = $('#ParamTbl').closest("tr").clone();
    clone.appendTo('#ParamTbl').find(":input").val(ParamName);
    $('#ParamTbl').closest("td").remove();
}

css('background-color','yellow');是出于调试目的,我也有几个alerts(),函数调用ok,ParamName交给它ok。所以,问题是:为什么我的行没有附加?

4

3 回答 3

2

http://api.jquery.com/closest/

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

请尝试find

var clone = $('#ParamTbl').find("tr:first").clone();

于 2013-04-19T11:50:23.143 回答
2

彻底的重新设计

HTML

<table id="ParamTbl">
    <tbody>
        <tr>
            <td><label for="paramname[]">Name: </label><input type="text" name="paramname[]" class="paramname"/></td>
            <td><label for="paramval[]">Value: </label><input type="text" name="paramval[]"/></td>
            <td><label for="paramtype[]">Type: </label><select name="paramtype[]">
                <option selected="true">String</option>
                <option>Double</option>
                <option>Object</option>
                </select></td>
            <td><div class="clrList">X</div></td>
            <td><div class="addrow">Add Param</div></td>
        </tr>
    </tbody>
</table>

JS

$(function(){
    var $table = $('#ParamTbl');

    $('#ParamTbl').on('click', '.addrow', function(){
        $table.css('background-color','yellow');

        var tr = $(this).closest('tr');

        var clone = tr.clone();
        clone.appendTo($table).find('input[name="paramval[]"]').val('');
        $(this).remove();
    })

    $('#ParamTbl').on('click', '.clrList', function(){
        $(this).closest('tr').remove()
    })
});

演示:小提琴

于 2013-04-19T11:53:27.967 回答
2

Try changing:

var clone = $('#ParamTbl').closest("tr").clone();

to:

var clone = $('#ParamTbl').find("tr#ParamRow").clone();

since closest() traversing up through its ancestors in the DOM tree.

于 2013-04-19T11:49:33.137 回答