jQuery.fn.add = function() {
var Bnumber = $(this).find(".B_Add");
if (Bnumber) {
Bcount = parseInt(Bnumber.html()) + 1;
$(this).find("div.B_Add").remove();
$(this).parent().find(".B_List").append('<div class="Badge B_Add">'+ Bcount +'</div>');
} else {
$(this).find(".B_List").append('<div class="Badge B_Add">1</div>');
}
}
I have a contextual menu script running, when i click on one of the options, it calls this function. It's supposed to see if the active element has this badge or not. If it does, it increments the integer value of the badge. Otherwise, it creates the badge starting at 1. The latter part is easy, the former harder.
I think i'm mixing up element types, and i'm not sure how to use parseInt...
EDIT
Figured it out.
jQuery.fn.add = function() {
if ($(this).find(".Badge").hasClass(".B_add")) {
bCount = parseInt($(this).find(".B_add").text());
$(this).find(".B_add").remove();
$(".OPT .B_list").append('<div class="Badge B_add">'+(bCount+1)+'</div>');
} else {
$(".OPT .B_list").app开发者_Python百科end('<div class="Badge B_add">0</div>');
}
}
Try this.
jQuery.fn.add = function() {
var Bnumber = $(".B_Add");
if (Bnumber) {
var Bcount = parseInt(Bnumber.html()) + 1;
Bnumber.html(Bcount);
} else {
$(this).find(".B_List").append('<div class="Badge B_Add">1</div>');
}
}
Try
Bcount = parseInt(Bnumber.text()) + 1;
Here's my take on it:
jQuery.fn.add = function() {
var badge = $('.B_Add', this);
if (badge.length) {
badge.html(Number(badge.html()) + 1);
} else {
$('.B_List', this).append('<div class="Badge B_Add">1</div>');
}
}
- Using the format
$('.B_Add', this)
for something inside of something else has always seemed the cleanest syntax to me. - You have to check for
badge.length
to see if an item was found - even when a jQuery selector matches no items, it still evaluates totrue
- There's no need to recreate the
B_Add
element, changing its content should accomplish the same thing. - I've never used
parseInt
in my life.Number
seems to do the same thing, and it looks nicer.
精彩评论