如果按类初始化,则select2触发两次 [英] select2 firing twice if initialized by class

查看:85
本文介绍了如果按类初始化,则select2触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用按钮从多个角度生成了select,所以我只能按班级识别它. 问题是,当select2:selectevent被触发时,如果被触发N次,则不仅在我更改值的地方也要发出警报.

I've several dinamically generated select using a button, so i can identify it only by class. The problem is that when select2:selectevent is fired, alert if fired N times, and not only where i changed the value.

如何解决? (我只能按类分配init插件,没有唯一的ID)

How solve this? (I only can assign init plugin by class, no unique id)

<a id="add">Add new</a>

 <div id="container">
 </div>


$(document).ready(function() {

  $("#add").on("click", function(e){
  e.preventDefault();

    $("#container").append('<select class="idFolder" name="idFolder[]"><option value="AL">Alabama</option><option value="WY">Wyoming</option></select>');

    $('.idFolder').select2({
    width: '100%'
  }).on('select2:select', function(e) {
    var id = e.params.data.id;
    alert(id);
  });

  });

});

以我的真实情况进行更新: https://jsfiddle.net/1jaw6d1x/3/

UPDATE with my real case: https://jsfiddle.net/1jaw6d1x/3/

推荐答案

您使用的解决方案涉及对所有select元素进行迭代,然后拾取要定位的元素,可以避免使用来对所有select进行迭代.each().您可以使用counter来避免这种情况,并且仅在较新的元素上绑定一次select2.

The solution you have used involves iterating on all the select elements and then picking up the one you are trying to target you can avoid iterating on all of the selects using .each(). You can use a counter to avoid this situation and only bind the select2 once on the newer element only.

这样,您将不必迭代所有选择,并且您已经具有要从集合中选择的元素的索引,想象在第51个选择处添加50个或更多选择.each()将首先迭代所有50个,然后然后到达第51位,然后绑定select2.

That way you won't have to iterate all the selects and you would have already the index of the element to select from the collection, imagine adding 50 or more selects at 51st select it.each() would iterate all 50 first and then reach the 51st and then bind select2.

var objectS = $(".idFolder");

var currentSelect=    $(objectS[count]);

请参阅下面的演示

var count = 0;
$(document).ready(function() {

  $("#add").on("click", function(e) {
    e.preventDefault();

    $("#container").append('<select class="idFolder" name="idFolder[]"><option value="AL">Alabama</option><option value="WY">Wyoming</option></select>');
    var objectS = $(".idFolder");
    var currentSelect = $(objectS[count])

    currentSelect.select2({
      width: '100%'
    }).on('select2:select', function(e) {
      var id = e.params.data.id;
      alert(id);
    });
    count++;
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<a id="add">Add new</a>

<br><br>

<div id="container">


</div>

这篇关于如果按类初始化,则select2触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆