javascript - 3 选择元素,但产生 6 值。为什么?

标签 javascript jquery

我有这个 HTML 结构:

<div id="kurir_list">
    <div class="row">
        <div class="col-sm-6">
          <div class="form-group form-group-default form-group-default-select2 required">
            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>
          </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-6">
          <div class="form-group form-group-default form-group-default-select2 required">
            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>
          </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-6">
          <div class="form-group form-group-default form-group-default-select2 required">
            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>
          </div>
        </div>
    </div>
</div>

我有这个 jquery :

$(".tarif").change(function() {
    $(".tarif").each(function() {
        alert ($(this).val());
    }); 
});

为什么警报产生 6 次对话框,而不是 3 次?

  • 第一:空
  • second : 第一个选择元素的 1 或 2
  • 第三个:空
  • 第四个:第二个选择元素的 1 或 2
  • 第五个:空
  • 第六个:第三个选择元素的 1 或 2

如何获取所选元素的精确值并忽略空值?请注意,这不仅仅是 HTML 选择,而是使用 Select2插件。

更新:这是我完整的 javascript 代码

(function($) {

    'use strict';

    $(document).ready(function() {

        $('#rootwizard').bootstrapWizard({
            onTabShow: function(tab, navigation, index) {
                var $total = navigation.find('li').length;
                var $current = index + 1;

                // If it's the last tab then hide the last button and show the finish instead
                if ($current >= $total) {
                    $('#rootwizard').find('.pager .next').hide();
                    $('#rootwizard').find('.pager .finish').show().removeClass('disabled hidden');
                } else if ($current == 2) {

                    if ($(".tarif").is(":disabled")) {
                        $('#rootwizard').find('.pager .next').hide();
                        $('#rootwizard').find('.pager .finish').hide();
                    }

                    $(".tarif").change(function() {
                        if ($(".tarif").is(':disabled')) {
                            $('#rootwizard').find('.pager .next').hide();
                        } else {

                            var emptySelect = false;
                            $('#kurir_list select').each(function(){
                                if (!$(this).find('option:selected').val()) {
                                    emptySelect = true;
                                }
                            });

                            if (emptySelect == false ) {
                                $('#rootwizard').find('.pager .next').show();
                            } else {
                                $('#rootwizard').find('.pager .next').hide();
                            }
                        }

                        $(".tarif").each(function() {
                            alert ($(this).val());
                        });

                        var selected_tarif = $(this).val();
                        var ongkir2 = $("#ongkir2").text();
                        ongkir2 = ongkir2.replace(/\D/g,"");

                        var new_ongkir2 = parseInt(ongkir2) + parseInt(selected_tarif);
                        new_ongkir2 = addCommas(new_ongkir2);
                        $("#ongkir2").text("Rp "+new_ongkir2);
                    });

                    $(".kurir").change(function() {
                        var selected_courier = $(this).val();
                        var token = $(this).data('token');
                        var productid = $(this).data('productid');
                        var city = $("#city").val();
                        var area = $("#area").val();
                        var quantity = $(".orderlist2").find("."+productid).find(".quantity").text();
                        quantity = quantity.replace(/\D/g,"");

                        var json_url = "SOME URL HERE";
                        $.ajax({
                            url: json_url,
                            dataType: "JSON",
                            success: function(json){

                                var rate_tarif = "";
                                var selected_tarif = "";

                                $.each(json, function(i,o){
                                    rate_tarif += "<option value="+o.tarif+">"+o.rate+"</option>";
                                });

                                $("#tarif-"+productid).append(rate_tarif).change();

                                event.preventDefault();
                                $("#tarif"+productid).prop("disabled", false);

                                selected_tarif = $("#tarif-"+productid).val();
                            }
                        });
                    });

                    $("#state").change(function() {
                        $('#rootwizard').find('.pager .next').hide();
                    });

                } else {
                    $('#rootwizard').find('.pager .next').show();
                    $('#rootwizard').find('.pager .finish').hide();
                }
            },
            onNext: function(tab, navigation, index) {
                console.log("Showing next tab");
            },
            onPrevious: function(tab, navigation, index) {
                console.log("Showing previous tab");
            },
            onInit: function() {
                $('#rootwizard ul').removeClass('nav-pills');
            }

        });
    });

})(window.jQuery);

最佳答案

您随后的评论对此进行了解释:

what you have is plain HTML, while in my case is using Select2 plugins

select2 的工作方式,它隐藏您的 select 元素(不删除它们)并创建一个新结构,将您的类等复制到其中。因此,您最终会得到 HTML 中的 .tarif 元素,以及由 select2 创建的 .tarif 元素。

您可以通过缩小选择器范围来限制您回复的对象:

$("select.tarif").change(function() {
    $("select.tarif").each(function() {
        alert ($(this).val());
    }); 
});

您可以在他们的示例页面上看到 select2 做了什么。

这是第一个例子的“之前”:

<select class="js-states form-control">
  <!--...options and such...-->
</select>

这是“之后”:

<select class="js-example-basic-single js-states form-control select2-hidden-accessible" tabindex="-1" aria-hidden="true">
      <!--...options and such...-->
</select>
<span class="select2 select2-container select2-container--default" dir="ltr" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-438s-container"><span class="select2-selection__rendered" id="select2-438s-container" title="Alaska">Alaska</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

请注意原始的 select 是如何隐藏的,js-statesform-control 类是从 select 中复制的 到 select2 生成的 span

关于javascript - 3 选择元素,但产生 6 值。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745488/

相关文章:

Javascript:从购物车中减去商品会导致负值

php - 需要从站点禁用自动下载器

javascript - "/"onclick事件时从URL中删除

javascript - 使用 jQuery 和 Javascript 的多个 API 调用架构

javascript - 异常 : Cannot read property 'addInstrumentToStage' of undefined

javascript - 互联网浏览器 : Can't Access IFrame Contents Unless Status Code is 200

javascript回调函数,变量映射

jquery - 不应该在桌面上调整流动布局的屏幕尺寸显示网站应该如何寻找移动设备?

javascript - 保存数据Jquery后如何避免确认窗口?

java - 为什么Javascript没有线程?