I’m pretty new to javascript and jquery, and have run into a problem that I have not yet found a solution for. I’ll attempt to paint it in a fairly simple way.
I have a page that offers the user a few choices (its a game, so..) like attack or defend, what weapon to use. It then loads two html ‘s, each with a “commit” button. The commit buttons are tied to (separate) functions that pass data to ajax.
The problem I have is that I’m getting buried in nested functions. Does that make sense? My code looks something like this:
code:
$(function() {
$('#choice1').click(function() {
//do some stuff
});
$('#choice2').click(function() {
//do some stuff
});
$('#choice3').click(function() {
//do some stuff, including creating the choices below, and their submit boxes
$('#subChoice1').click(function() {
//send data with ajax to a php document. get result
//create some text on my document to display results
//create an input button, along with an id="subButton1"
});
$('#subChoice2').click(function() {
//send data with ajax to a php document. get result
//create some text on my document to display results
//create an input button, along with id="subButton1"
//(yes, feed both back to same func)
});
}); // end choice3
$('#subButton1').click(function() {
//my buttons in the subChoices do not call this function(!!??)
});
});
edit: link no longer works, sorry. And I’ve created a living example here.
Thanks for any tips or pointers. I’m almost certain that there is just something simple that I’m missing or unaware of that will get me on the right track.
You could always use normal named functions instead of inline anonymous ones. That might help if the mountain of functions is getting too tall.
Update:
Here’s your working Case 1:
What I’m proposing is to update it like this:
That way the structure of the logic stays the same, but you can pull out the nested function definitions.