问题
I have a div that I want to show only if a certain value is selected from a drop down menu ( in this case , it is custom-css )
On the fiddle ( http://jsfiddle.net/obmerk99/8xnzh/1/ ) it works ok...
jQuery(document).ready(function() {
jQuery("#k99-custom-1").change(function () {
jQuery("#k99-custom-1 option:selected").each(function ()
{
if( jQuery(this).attr("value") == "custom-css")
{
jQuery("#customcss").show();
}
else
{
jQuery("#customcss").hide();
}
});
}).change();
});
but in the real page , the select drop down is actually generated dynamically with an "add option" button , so that certain (first) select does not exists on page load (document ready ) and I think that this is the reason that it does not work ..
see the full one here in action ( not working ) : http://jsfiddle.net/obmerk99/ZcAzy/1/
What am i doing wrong in order to have the div shown if the "custom-css" value is selected ? ( now it is set to work only with the first one ( or second ) - but it would be great to make it work with all of the added select lists .. )
回答1:
Try using delegation, like so:
jQuery(function() {
// Here, `.on` is used in its `delegate` form, where it asigns an event to any
// element matching the selector
// regardless when it was added to the DOM
jQuery(document).on('change', "[id^='k99-custom-']", function(e) {
jQuery("[id^='k99-custom-'] option:selected").each(function(i) {
if (jQuery(this).attr("value") == "custom-css") {
jQuery("#customcss").show();
}
else {
jQuery("#customcss").hide();
}
});
})
})
I just noticed in a comment on another answer, you tried something like this. What you did wrong was to delegate the event of selector [id^='k99-custom-'] to [id^='k99-custom-'], which, as you can see, is itself. To delegate, you need to asign to either a parent element or the document itself, as in my example. The most common use is simply to use $(document).on(...
Example
Learn more about .delegate and the .on form of it!
回答2:
You need to use the on function instead of just change to bind to dynamic elements.
$('body').on('change','#k99-custom-1',function(){
//function here
});
来源:https://stackoverflow.com/questions/17434793/changing-div-visibility-based-on-select-box