1
我需要使用jQuery獲取div數量的長度。jquery添加長度和刪除點擊次數
我可以得到它,但在兩個點擊事件中聲明變量,但這似乎是錯誤的,我也需要使用它來顯示隱藏一個按鈕取決於數量。我覺得我不應該把代碼翻倍。
小提琴這裏
https://jsfiddle.net/4Lqsf45a/51/
$("button#add").click(function(e) {
e.preventDefault();
$(document.body).append($("<div>"));
var n = $("div").length;
$("span").text("There are " + n + " divs.");
if (n < 2) {
$('#showhide').hide()
} else {
$('#showhide').show()
}
});
$("body").on("click", "div", function(e) {
e.preventDefault();
$(this).closest("div").remove();
var n = $("div").length;
$("span").text("There are " + n + " divs.");
if (n < 2) {
$('#showhide').hide()
} else {
$('#showhide').show()
}
});
如果您不想複製代碼,則將其移至某個函數並調用該函數。 – nurdyguy