使用javascript删除行时出错?

时间:2012-06-13 09:14:15

标签: javascript jquery

我有一个示例代码:

<input type="checkbox" id="input_modem_1" onclick="add_delete_row(this, 1,'test1' )" name="modem_id[]" value="1" /> test 1
<input type="checkbox" id="input_modem_2" onclick="add_delete_row(this, 2,'test2' )" name="modem_id[]" value="2" /> test 2
<table id="modem_list"></table>

代码javascript:

<script>
function add_delete_row(element, id, modem_name) {
    if(element.checked) {
        if(id) {
            deleteRow(id);
        }
        addRow(id, modem_name);
    } else {
        deleteRow(id);
    }
}
function addRow(id, modem_name) {
    var table = document.getElementById("modem_list");

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "checkbox";
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "hidden";
    element2.value = id;
    cell2.innerHTML = modem_name;
    cell2.appendChild(element2);
}
function deleteRow(id) {
    try {
        $('modem_list').removeChild($('modem_'+id));
        $('modem_list').removeChild($('input_modem_'+id));
    } catch(err){}
}
</script>  

当我检查一个值是结果时添加一行,当我取消选中这一行时,结果没有运行,它会添加更多这个,如何解决它

3 个答案:

答案 0 :(得分:0)

您无法使用此代码: 在function addRow()中添加:

var row = table.insertRow(rowCount);
row.className = "input_"+id; // with id is 1, 2, ...n

function deleteRow(id) {
    try {
        jQuery(".input_"+id).remove();
    } catch(err){}
}

答案 1 :(得分:0)

如果要使用jQuery按ID选择元素,则需要使用哈希符号。那是

$('#modem_list')

不是

$('modem_list')

答案 2 :(得分:0)

row.setAttribute("name","modem_"+id);

之后添加var row = table.insertRow(rowCount);

function deleteRow(id)替换为下一个

function deleteRow(id) {
    var table = document.getElementById("modem_list");
    var rowName = 'modem_'+id;
    if (table.rows.namedItem(rowName)) {
        table.deleteRow((table.rows.namedItem(rowName).rowIndex));
    }
}

没有jquery