2

我正在尝试编写一些代码,如果 #hold 占位符 div 中的直接子 div 少于 3 个,则仅允许单击具有 .add 类功能的按钮。theDiv_append 是一个单独的函数,它在#hold div 占位符中添加一个 div 块。我正在尝试更新countingdivs 变量,然后计算并更新#hold 中的div 数,但它不起作用。目前,添加按钮不会被禁用。

   var countingdivs = '1'; 
    if(countingdivs <= '2') {
  $(document).on('click',".add",theDiv_append);
    countingdivs = $("#hold > div").length;
   };

任何帮助都会很棒。谢谢!

4

2 回答 2

0

尝试:

var countingdivs = 1; 
if(countingdivs <= 2) {
    $(document).on('click',".add", theDiv_append);
    countingdivs = $("#hold > div").length;
} else {
    $(document).off('click',".add", theDiv_append);
}

也许尝试分配countingdivs当前长度#hold > div

var countingdivs = $("#hold > div").length;
于 2013-07-14T21:25:49.973 回答
0

将条件移动到点击处理程序:

$(document).on('click', '.add', theDiv_append);

function theDiv_append() {
    var $hold = $('#hold'),
        len = $hold.children('div').length;

    if (len <= 2) {
      // ...
    }
}
于 2013-07-14T21:28:52.283 回答