I'm trying to append an increasing number to elements on click. I can't seem to make it work.
My code:
$('#on').click(function() {
$("b").click(function(e) {
var numCount = ($("[span class='num'>").length + 1);
var element = $("<span class='num'>" + numCount + "'>" + numCount + "</span>");
$(this).append(element);
});
});
I think It's a simple syntax error in my code, but I'm learning here so I could be completely wrong. It's important for the class to be added too.
Change
var numCount = ($("[span class='num'>").length + 1);
to
var numCount = ($(".num").length + 1);
You need to find .num
elements, not create new ones.
In addition, your element
line doesn't create valid HTML either. Try the following:
var element = $("<span class='num'>" + numCount + "</span>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.