【问题标题】:Append List Item Count jQuery追加列表项计数jQuery
【发布时间】:2012-08-30 01:11:25
【问题描述】:

我正在使用它来根据多个选择框的值填充列表:

$(document).ready(function() {
    $("select").change(function() { // <-- bind change event handler to the drop downs
        var sel = "";
        $(".option-select option:selected").each(function() { // <-- then iterate each time it changes   
            if ($(this).index() !== 0) { // <-- only if not default
                sel += "<li>" + $(this).text() + "</li>";
            }
            $("ul.result ul").empty().append(sel); //<-- empty() to remove old list and update with new list
        });
    });
});​

但是,我不知道如何打印添加到列表中的选项数量,或选择值的选择框数量。我需要告诉用户他们选择了多少选项,并像我一样显示这些选项。我发现了如何使用以下方法计算列表中的项目数:

var count = $("ul li").length;

但无法弄清楚如何打印此计数。

【问题讨论】:

    标签: jquery printing count append populate


    【解决方案1】:

    可以这样做

        $(document).ready(function() {
        $("select").change(function() { // <-- bind change event handler to the drop downs
            var sel = "";
            var counter = 0;
            $(".option-select option:selected").each(function() { // <-- then iterate each time it changes   
                if ($(this).index() !== 0) { // <-- only if not default
                {
                    sel += "<li>" + $(this).text() + "</li>";
                    counter++;
                }
                }    
                $("ul.result ul").empty().append(sel); //<-- empty() to remove old list and update with new list
            });
        });
    
    //The Number of Option's Added
    counter;
    

    或者只是将enter code here sel 转换为 Jquery

    $(sel).length;
    

    【讨论】:

      【解决方案2】:

      我会创建一个元素并将值放入其中,如下所示:

      <div id="count_holder">You have <span></span> options</div>
      <script>
          $("#count_holder").find("span").text(count);
      </script>
      

      【讨论】:

        【解决方案3】:

        也许你想要这样的东西

        $(document).ready(function() {
            $("select").change(function() {
                var list=$(this).children(':selected').not($(this).children()[0]);
                $('#result, #count').empty();
                if(list.length){
                    list.each(function(){
                        $('<li></li>').val($(this).val()).text($(this).text())
                        .appendTo($('#result'));
                        $('#count').html(list.length);
                    });
                }
            });
        });
        

        DEMO.

        【讨论】:

          猜你喜欢
          • 2015-06-12
          • 2013-05-14
          • 1970-01-01
          • 1970-01-01
          • 2014-06-07
          • 1970-01-01
          • 2013-04-16
          • 1970-01-01
          • 2018-02-05
          相关资源
          最近更新 更多