【问题标题】:HTML/Jquery How to limit number of child divs?HTML/Jquery 如何限制子 div 的数量?
【发布时间】:2014-06-06 18:22:01
【问题描述】:

我有 3 页。每个页面都有一个相同类的父 div。用户可以从一页水平滚动到另一页。此外,用户可以将子 div 动态添加到父容器中。 用户将开始从父级添加 div(在第 1 页)。

我有两个问题:

  1. 使用 jquery 如何将子 div 的数量限制为 3。如果用户尝试添加另一个,则会将其添加到第 2 页(除非第 2 页有 3 个子 div,否则它将转到第 3 页) ?

  2. 一旦第 3 页的父容器已满(3 个 div),就会弹出一个警告,提示“您不能再添加 div!!”。

请帮助我。我是所有这些东西的新手。

提前致谢。

相关图片:

示例代码::

 <script>
$("addbutton").click(function(){
$("#child").appendTo(".parent");
});
</script>


//page 1
<div class= "parent">
<div id= "child1">
</div>
<div id= "child2">
</div>
<div id= "child3">
</div>
</div>

//page 2
<div class= "parent">

</div>

//page 3
<div class= "parent">

</div>

【问题讨论】:

  • 添加了示例代码。感谢您的关注。

标签: javascript jquery html css


【解决方案1】:

http://jsfiddle.net/w6AAq/

if($(".parent").children().length < 4) {
     console.log('Less then or equal to 3')   
}else {
     console.log('Cannot add any more child elements')   
}

【讨论】:

    【解决方案2】:

    这是我想出的方法:

    var $pages = $('.page');
    var child = '<div class="child"></div>';
    
    $('button').on('click', function () {
    
      var childAdded = false;
    
      $pages.each(function () {
        var $page = $(this);
        if ($page.children().length < 3) {
          $page.append(child);
          childAdded = true;
          return false;
        }
      });
    
      if (!childAdded) {
        alert('You can not add anymore divs!');
      }
    
    });
    

    我遍历每个.page 并检查孩子的数量。如果孩子少于 3 个,我添加一个,然后通过返回 false 退出循环。

    带有一个小演示:http://jsbin.com/nuyipuya/3/edit

    【讨论】:

    • 感谢您的回复。 :-)
    【解决方案3】:

    试试这个

    $("addbutton").click(function(){
        if($(".parent").children().length<3)
    {
        $("#child").appendTo(".parent");
    }
    else
    {
          alert("You can not add any more divs");
    }
        });
    

    http://api.jquery.com/children/

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多