jquery dropdown image help
I have a dropdown country list using the jquery and stuff at http://jsfidd开发者_如何学Gole.net/josh3736/jf5QK/ however in that demo and mine when you select one from the dropdown, it doesn't change the flag image, and it only briefly changes the country name? I've tried playing with it to no avail.
Any help?
The country changes back because the form is posted and the dropdown is rebuilt when a country is chosen. The click event seems to propagate to something that is posting the form. This can be prevented by adding a e.preventDefault() to the click function:
// when a language is clicked, make the selection and then hide the list
$(".dropdown dd ul li a").click(function(e) {
var clickedValue = $(this).parent().attr("class");
var clickedTitle = $(this).find("em").html();
$("#target dt").removeClass().addClass(clickedValue);
$("#target dt em").html(clickedTitle);
$languageList.hide();
$dropTrigger.removeAttr("class");
e.preventDefault();
});
I'll try to look into it some more to try to find out why the flag isn't changing.
Edit: Seems as if someone else posted the solution to the flag issue before me :P
Anyway, this was the solution that I came up with:
var clickedValue = $('em', this).attr("class");
The flag isn't changing because you aren't getting the class for the flag image like you expect in the .click(). If you change your click() like I have below, you will get the new name and flag like you expect:
// when a language is clicked, make the selection and then hide the list
$(".dropdown dd ul li a").click(function() {
var clickedValue = $(this).find("em").attr("class");
var clickedTitle = $(this).find("em").html();
$("#target dt em").removeClass().addClass(clickedValue);
$("#target dt em").html(clickedTitle);
$languageList.hide();
$dropTrigger.removeAttr("class");
});
});
The form is posting back which causes everything to get rebuilt which is what then resets the flag and country name.
To be honest I'm going to vote up both the other efforts because they are good solutions, but I don't think your code is going wrong - its the postback after the click that is causing the problem. A simple return false; should stop that.
// when a language is clicked, make the selection and then hide the list
$(".dropdown dd ul li a").click(function() {
var clickedValue = $(this).parent().attr("class");
var clickedTitle = $(this).find("em").html();
$("#target dt").removeClass().addClass(clickedValue);
$("#target dt em").html(clickedTitle);
$languageList.hide();
$dropTrigger.removeAttr("class");
return false;
});
});
精彩评论