I try to make a click event with jquery.
The result I want is shown below:
first click - plus one
second click - plus one
third click - plus one & change of button's id and text
fourth click onward - plus one & alert pop-out
However, the alert pop-out at the third click.
my html:
<h1 id="number">0</h1>
<button id="next">Add 1</button>
my jquery:
$(document).ready(function () {
let num = 0;
$("#next").click(function () {
num;
if (num > 2) {
$("#next").html("Alert");
$("#next").attr('id', 'alert');
$("#number").html(num);
} else {
$("#number").html(num);
}
});
$(document).on("click", "#alert", function () {
alert(num);
});
});
I don't know where I went wrong, in theory this looks fine to me but I am new to jquery and I must have missed something.
CodePudding user response:
On the third click
- call
e.stopPropagation()
to prevent the#next
click event being propogated to#alert
element. - unbind the
#next
click event using$("#next").unbind("click");
or else$("#next").click
will be triggered on clicking#alert
Also dont forget to handle the alert and increment logic inside "#alert"
click event.
Working Fiddle
$(document).ready(function () {
let num = 0;
$("#next").click(function (e) {
num;
if (num > 2) {
$("#next").unbind("click");
$("#next").html("Alert");
$("#next").attr('id', 'alert');
$("#number").html(num);
e.stopPropagation();
} else {
$("#number").html(num);
}
});
$(document).on("click", "#alert", function () {
num;
alert(num);
$("#number").html(num);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h1 id="number">0</h1>
<button id="next">Add 1</button>
CodePudding user response:
You can try following code:
$(document).ready(function () {
let num = 0;
$(document).on("click", "#next", function () {
num ;
if (num > 2) {
$("#next").html("Alert");
$("#next").attr('id', 'alert');
$("#number").html(num);
}
else {
$("#number").html(num);
}
});
$(document).on("click", "#alert", function () {
num ;
$("#number").html(num);
alert(num);
});
});
Hope it will work.