问题
I am familiar with using "on" for making sure my jquery methods are active (since I render pages via Ajax).
Ex:
$('body').on( 'click', '#demobutton', function (event) {
alert("CliCKED!");
});
However I need to do the same for jQuery Multiselect. Below works only when the page is reloaded. However if my content is loaded via Ajax, MultiSelect does not render at all.
$("select").multiselect({
click: function(event, ui){
alert(ui.value + ' ' + (ui.checked ? 'checked' : 'unchecked') );
},
beforeopen: function(){
$callback.text("Select about to be opened...");
},
open: function(){
$callback.text("Select opened!");
},
beforeclose: function(){
$callback.text("Select about to be closed...");
},
close: function(){
$callback.text("Select closed!");
},
checkAll: function(){
$callback.text("Check all clicked!");
},
uncheckAll: function(){
$callback.text("Uncheck all clicked!");
},
optgrouptoggle: function(event, ui){
var values = $.map(ui.inputs, function(checkbox){
return checkbox.value;
}).join(", ");
alert("CheckboXES " + (ui.checked ? "checked" : "unchecked") + ": " + values);
}
});
So the question is how to rewrite above using a format such as $('body').on ? Thanks for any help. Newbie here!
回答1:
since you specified (However if my content is loaded via Ajax, MultiSelect does not render at all.)
here i am loading select options with ajax and binding multiselect jsfiddle . Let me know if this helps you.
$(document).ready(function(e) {
var form_data = $("#frm").serialize();
var form_url = $("#frm").attr("action");
var form_method = $("#frm").attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
alert('binded options to select on ajax success');
$.when(assignOptions()).done(function(){
bind();
});
}
});
});
function assignOptions(){
$("#display_list").append('<option value="W1">VICccccc</option><option value="W2">NSW</option><option value="W6">TAS 3</option>');
}
function bind(){
$("select").multiselect({
click: function(event, ui){
alert(ui.value + ' ' + (ui.checked ? 'checked' : 'unchecked') );
},
beforeopen: function(){
$callback.text("Select about to be opened...");
},
open: function(){
$callback.text("Select opened!");
},
beforeclose: function(){
$callback.text("Select about to be closed...");
},
close: function(){
$callback.text("Select closed!");
},
checkAll: function(){
$callback.text("Check all clicked!");
},
uncheckAll: function(){
$callback.text("Uncheck all clicked!");
},
optgrouptoggle: function(event, ui){
var values = $.map(ui.inputs, function(checkbox){
return checkbox.value;
}).join(", ");
alert("CheckboXES " + (ui.checked ? "checked" : "unchecked") + ": " + values);
}
});
}
来源:https://stackoverflow.com/questions/23577327/jquery-multiselect-delegate-event-using-on