开发者

Increment Badge Count

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>');
    }
}
  1. Using the format $('.B_Add', this) for something inside of something else has always seemed the cleanest syntax to me.
  2. 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 to true
  3. There's no need to recreate the B_Add element, changing its content should accomplish the same thing.
  4. I've never used parseInt in my life. Number seems to do the same thing, and it looks nicer.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜