问题
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.
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);
});
});
});
UPDATE with my real case: https://jsfiddle.net/1jaw6d1x/3/
回答1:
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.
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]);
See demo below
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>
回答2:
Solved:
$(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').each(function(){
if ($(this).hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
} else {
$(this).select2({
width: '100%'
}).on('select2:select', function(e) {
var id = e.params.data.id;
alert(id);
});
}
});
});
});
来源:https://stackoverflow.com/questions/50394027/select2-firing-twice-if-initialized-by-class