I wrote the code in javascript (jQuery), that allows a user with every click of a button to create a "box" on the web site and to get an alert message after this box was clicked.
It works like this: 1) When the user presses the button "Add (#addBox)" - jQuery appends a new line to the HTML file, that creates the "box" (it looks like a box because of the CSS code). 2) If the user presses the box, it sends out the alert message "Hello".
But if I add multiple boxes and then click on the first one, instead of sending out one alert message, it sends it out as many time as the number of boxes been created.
Example: 1) I have 1 box. By pressing on it, I receive 1 alert message. 2) I have 2 boxes. By pressing on the top one, I receive 2 alert messages. By pressing on the second one, I receive 1 message. 3) I have 3 boxes. By pressing on the top one, I receive 3 alert messages. By pressing on the second one, I receive 2 messages. By pressing on the third one, I receive 1 message.
The function of sending an alert message is looping for some reason. And so here is the code:
function addBox()
{
$("#addBox").on("click", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
}
boxCount();
});
}
function boxCount()
{
$(".desiredBox").on("click", function () {
alert("Hello");
});
}
Any ideas, how to make them send only one message each, preventing the function "boxCount()" from looping?
Aucun commentaire:
Enregistrer un commentaire