我想通过单击单元格然后单击添加按钮来在特定位置添加列。 问题是,当我第一次单击该按钮时,结果是正确的,并且我在我选择的位置添加了我的列。但是,当我尝试在另一个位置添加另一个列时,单击添加按钮后,我有两个新列,但我只想要一个......当我第三次单击时,我得到三个......它是这样的... n 单击... n 列,我不知道为什么以及如何解决这个问题... 请帮忙 !! 这是代码:
$(document).ready(function ()
{
//my function to create my table
$("#btn-create-table").click(function create_new_table(){
var nb_columns = document.getElementById("columns").value;
var nb_rows = document.getElementById("rows").value;
var table=document.createElement("table");
$(table).attr("element", "table");
$(table).append(thead=document.createElement("thead"));
$(thead).append(line=document.createElement("tr"));
for (var j=0; j<nb_columns;j++) {
$(line).append(document.createElement("th"));
};
$(table).append(tbody=document.createElement("tbody"));
for(var j=0;j<nb_rows;j++){
$(tbody).append(line=document.createElement("tr"))
for (var k=0; k<nb_columns;k++) {
$(line).append(td=document.createElement("td"));
};
};
var span=document.createElement("span");
$(span).append(input=document.createElement("input"));
$(input).attr("type","button");
$(input).attr("name","addcolumn[]");
$(input).attr("value","+");
$(input).addClass("addColumn");
$("#content").append(table);
$("#content").append(span);
});
//Add column in specific position
$(document).on('click','[element="table"] td', function add_column (){
num_column = $(this).index();
$("span .addColumn").click(function () {
$('[element="table"]').find('tr').each(function(){
$(this).find('th').eq(num_column).after('<th>newTH</th>');
$(this).find('td').eq(num_column).after('<td>newTD</td>');
});
});
});
});
table {
border-collapse: collapse;
width: 100%;
height: 60px;
}
table td {
border-width: 1px;
border-style: solid;
border-color: grey;
height: 60px;
text-align: center;
}
table thead {
width: 100%;
height: 60px;
background-color: rgba(0, 0, 255, 0.2);
}
table th {
border-width: 1px;
border-style: solid;
border-color: grey;
height: 60px;
text-align: center;
}
input.addColumn {
-moz-border-radius: 4px;
border-radius: 4px;
background-color:#99ffff;
-moz-box-shadow: 0 0 4px rgba(0, 0, 0, .75);
box-shadow: 0 0 4px rgba(0, 0, 0, .75);
width:25px;
}
input.addColumn:hover {
background-color:#00ffff;
-moz-border-radius: 4px;
border-radius: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
<label for="columns">
<input id="columns" type="number" min="1" placeholder="columns"></input>
</label>
<br />
<label for="rows" class="">
<input id="rows" type="number" min="1" placeholder="rows"></input>
</label>
<br />
<button id="btn-create-table">create</button>
<div id="content" contentEditable="true">
</div>
最佳答案
尝试像这样编辑你的代码:
$("span .addColumn").unbind().click(function () {
我在点击之前添加了“unbind()”方法调用
关于javascript - 如何在特定位置动态添加列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682231/