2017-08-11 22 views
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() 
    } 

}); 
+0

如果您不想複製代碼,則將其移至某個函數並調用該函數。 – nurdyguy

回答

2

爲了保持DRY可以提取與共同邏輯出了自己的功能和調用它需要的地方:

$("button#add").click(function(e) { 
 
    e.preventDefault(); 
 
    $('body').append('<div>'); 
 
    countDivs(); 
 
}); 
 

 
$("body").on("click", "div", function() { 
 
    $(this).closest("div").remove(); 
 
    countDivs(); 
 
}); 
 

 
function countDivs() { 
 
    var n = $("div").length; 
 
    $("span").text("There are " + n + " divs."); 
 
    $('#showhide').toggle(n >= 2); 
 
}
div { 
 
    width: 50px; 
 
    height: 30px; 
 
    margin: 5px; 
 
    float: left; 
 
    background-color: green; 
 
} 
 

 
span { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span></span> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 

 
<button id="add"> 
 
    add 
 
</button> 
 

 
<p> 
 
    <button id="showhide"> 
 
    show/hide 
 
    </button> 
 
</p>

否我刪除preventDefault()div點擊處理程序,因爲它不是必需的。在button點擊處理程序中可以說沒有必要 - 假設按鈕的生產版本不包含在窗體中,如您的示例中所示。

+0

很酷,很好,謝謝 – user3665791