gpt4 book ai didi

javascript - 如何在选中复选框的行之后插入行

转载 作者:行者123 更新时间:2023-12-02 22:04:38 25 4
gpt4 key购买 nike

我需要能够在检查的行之后直接插入一行。下面列出了 HTML,这里是 JSFiddle 。基本上,如果选中第 1 行,我需要在第 1 行和第 2 行之间插入一行,或者如果选中最后一行,我需要追加一个新行。我能够编写一个脚本,在表末尾添加一行,但这不是我需要的。

<INPUT type="button" value="Add Row" onclick="addRow('requestTable')" />

<TABLE id="requestTable">
<tr>
<th></th>
<th>Example column</th>
<th>Example column 2</th>
</tr>

<tr>
<td><input type="checkbox" /></td>
<td><input name="Example1" /></td>
<td><input name="Example2" /></td>
</tr>

<tr>
<td><input type="checkbox" /></td>
<td><input name="Example1" /></td>
<td><input name="Example2" /></td>
</tr>
</TABLE>

<script>
function addRow(tableID) {

var table = document.getElementById(tableID);

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

var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {

var newcell = row.insertCell(i);

newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
</script>

最佳答案

这将按照您的要求进行:它将在选中的行之后添加一个新行,如果选中多行,则不会添加一行:

Html:我修改了它,在添加按钮上有一个 id 属性,用于添加事件处理程序,并向您的复选框添加了一个公共(public)类名。:

<INPUT id="btnAdd" type="button" value="Add Row" />

<TABLE id="requestTable">
<tr>
<th></th>
<th>Example column</th>
<th>Example column 2</th>
</tr>

<tr>
<td><input class="chkInfo" type="checkbox" /></td>
<td><input name="Example1" /></td>
<td><input name="Example2" /></td>
</tr>

<tr>
<td><input class="chkInfo" type="checkbox" /></td>
<td><input name="Example1" /></td>
<td><input name="Example2" /></td>
</tr>
</TABLE>

脚本:

//On DOM Ready add the click event to the Add Button
$(function(){
//Uses JQuery's .on to add eventHandler to the button when the DOM is ready
$('#btnAdd').on('click', function(){
addRow("requestTable");
});
});

//Modified the addRow metthod to look for the checked checkboxes
//with className of chkInfo, if the number of checked checkboxes is greater
//than 1 it does nothing, else it finds the parent row of the checkbox which is checked with JQuery's .closest()
//and uses JQuery's .after() to append the row after the checked row
function addRow(tableID) {
const checkboxes = $('#' + tableID).find('.chkInfo:checked');
if($(checkboxes).length === 1){
const newRow = '<tr><td><input class="chkInfo" type="checkbox" /></td><td><input name="Example1" /></td><td><input name="Example2" /></td></tr>';
$($(checkboxes)[0]).closest('tr').after(newRow);
} else{
return;
}

}

工作中的 JSFiddle ( https://jsfiddle.net/Lf5cbdt0/ )

关于javascript - 如何在选中复选框的行之后插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59755136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com