jQuery: Event function not taking variable?
if a radio button is selected, i want a div to either show or hide. here is the code:
// add event to hide unimportant details when var is disabled and show when enabled
$('#companyVar' + companyVarID + 'Enabled').change(function() {
$('#companyVar' + companyVarID + 'Unimportant').fadeIn("slow");
});
$('#companyVar' + companyVarID + 'Disabled').change(function() {
$('#companyVar' + companyVarID + 'Unimportant').slideUp("slow");
});
it should work (i a开发者_高级运维lert tested that the event actually runs), but i think that for some reason, the variable companyVarID
is unknown inside the event function. how can i fix this?
Well, you didn't bother giving us any context, but chances are, you're changing the value of companyVarID
after setting up these event handlers...
Somehow, you need to preserve that value (and not just the reference to the variable, which is adequately captured by the closure).
Nick's solution will work, and is fairly clean, but here's an alternate technique just to give you an idea of what's going on...
// ...something assigns a value to companyVarID
// put event-handler wireup in an anonymous function (to be called immediately)
// mask the outer variable with a parameter that can't be changed externally
(function(companyVarID)
{
// add event to hide unimportant details when var is disabled and show when enabled
$('#companyVar' + companyVarID + 'Enabled').change(function() {
$('#companyVar' + companyVarID + 'Unimportant').fadeIn("slow");
});
$('#companyVar' + companyVarID + 'Disabled').change(function() {
$('#companyVar' + companyVarID + 'Unimportant').slideUp("slow");
});
// pass the value of the outer variable to our anonymous function, allowing
// it to be captured in the event-handler closures
})(companyVarID);
// ...something changes the value of companyVarID
You can change it slightly, to be based of the current element's ID, like this:
$('#companyVar' + companyVarID + 'Enabled').change(function() {
$('#' + this.id.replace('Enabled', 'Unimportant')).fadeIn("slow");
});
$('#companyVar' + companyVarID + 'Disabled').change(function() {
$('#' + this.id.replace('Disabled', 'Unimportant')).slideUp("slow");
});
精彩评论