I have an array of buttons that when clicked on, opens or closes content on my site. I need to be able to track which one is open so that when I click on that button again, I will know whether or not to close the content.
Here's my array:
var imageOptions = ['.corporateNeeds', '.marketResearch', '.corpStrategic', '.employeeTraining', '.administration', '.wellnessManagement'];
And the content that will open once you click on one of the buttons.
var options = ['.option1', '.option2', '.option3', '.option4', '.option5', '.option6'];
Then I loop through the array and show the content of whichever one was clicked on:
jQuery.each(imageOptions, function (k) {
$(imageOptions[k]).click(function () {
hideOptions()
$(options[k]).fadeIn();
$(options[k].contentOpen) = true;
});
});
开发者_StackOverflow
What I want to know is if there is a way of tracking the current clicked button by dot syntaxing a variable i.e. ($(options[k].contentOpen) = true;) onto that array button. I know this can be done in AS, but I need to know how to do this in jQuery.
Thanks ;)
I'm not sure what you're trying to accomplish, but I'm assuming you need to keep a state for each button (open/closed) so you know if you need to open or close the associated content box.
For this, you can use the data() function in jQuery:
jQuery.each(imageOptions, function (k) {
$(imageOptions[k]).click(function() {
if ($(this).data("open") == "true") {
// hide content
$(this).data("open","false");
} else {
// show content
$(this).data("open","true");
}
});
});
why won't you use .data()
to store values?
example
$('button').click(function(){
if ($('div#window').data('contentOpen') ) {
// means open
$('div#window').data('contentOpen',false); // set it to close
// do something here
} else {
// means close
$('div#window').data('contentOpen',true); // set it to open
// do something here
}
})
you could create an array of anonym objects to accomplish this e.g.
var imageOptions = ['.corporateNeeds', '.marketResearch', '.corpStrategic', '.employeeTraining', '.administration', '.wellnessManagement'];
var options = [{ selector: ".option1", contentOpen: false }, { selector: ".option2", contentOpen: false }, { selector: ".option3", contentOpen: false }];
jQuery.each(imageOptions, function (k) {
$(imageOptions[k]).click(function () {
hideOptions()
$(options[k].selector).fadeIn();
options[k].contentOpen = true;
});
});
精彩评论