在下面的代碼片段中,我在它旁邊有一個輸入和一個刪除按鈕。它們可以被克隆,每個刪除按鈕都有一個函數,告訴我哪個輸入試圖被刪除。克隆的按鈕無法使用點擊功能
奇怪的是,當我運行代碼片段時,它完美地工作。
在我的瀏覽器中,克隆的按鈕沒有調用函數,只有原來的函數。另外,即使將鼠標懸停在任何其他按鈕上,「刪除」標題也只出現在第一個按鈕上。
什麼可能導致此問題?
我正在使用片段中所有內容的相同版本。
$("#clone").click(function() {
var currentCount = $("#tablePhones tbody tr").length;
var newCount = currentCount + 1;
$('#tablePhones tbody>tr:last').clone(true).insertAfter('#tablePhones tbody>tr:last');
$('#tablePhones tbody>tr:last').find("input, a").each(function() {
var newId = $(this).attr("id").replace("_" + currentCount, "_" + newCount);
var newName = $(this).attr("name").replace("_" + currentCount, "_" + newCount);
$(this).attr("id", newId).attr("name", newName);
if ($(this).is("input")) {
$(this).val("");
}
});
});
$(".btn.remove").click(function() {
name = $(this).attr("name");
console.log(name);
});
td .btn.aligned {
position: absolute;
margin-top: 7px;
float: right;
margin-left: 5px;
}
td input {
float: left;
margin-bottom: 10px;
}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://use.fontawesome.com/a06b1c7829.js"></script>
<a id="clone" class="btn btn-primary">
<i class="fa "></i> Clone
</a>
<table id="tablePhones" class="table table-hover">
<thead class="thead-inverse">
<th>Phone numbers</th>
</thead>
<tbody>
<tr>
<td>
<div class="row col-xs-3">
<input type="text" name="phone_1" id="telefono1_1" class="form-control" />
<a title="Remove" name="removephone_1" id="removephone_1" class="btn btn-danger btn-xs aligned remove"><span class="fa fa-times">
</span>
</a>
</div>
</td>
</tr>
</tbody>
</table>
您的代碼可以在我的Chrome 58中完美工作。 – wannadream
'.clone(true)'也應該克隆附加的任何事件偵聽器,所以您做得很對 - 並且您的代碼段可以正常工作。你能爲我們重現錯誤嗎? – mhodges
調試工作代碼非常困難。代碼段和項目代碼之間必須有不同的內容。 javascript是否被打斷? javascript控制檯是否會報告任何錯誤或警告? –