jQuery重复元素

时间:2012-11-05 18:12:22

标签: javascript jquery tags element

我的代码使用户可以选择最多5个标签,显示标签并计算数字。

$(document).ready(function(e) {

    var tagname = "";
    var count = 0;  

    $(".tagchoose").click(function(){ 
        count++;
        if(count < 6) {
        $("#tagselectshow").html("Tags Selected: " + count + " tags selected");
        tagname = "<span class='selectedtg'>" + $(this).html() + "</span> / ";
        $("#displaythetags").append(tagname);
        }
    });

    $("#deletetags").click(function(){ 
        count = 0;  
        tagname = "";

        $("#tagselectshow").html("Tags Selected: " + count + " tags selected");
        $("#displaythetags").html(tagname); 
    });

});

不幸的是,目前代码不限制选择重复标签,我想为用户添加限制,以便无法选择相同的标签。

2 个答案:

答案 0 :(得分:1)

您可以将所选标签保留在数组(标签)中,然后在用户添加标签时检查该项是否在数组中。

$(document).ready(function(e) {

    var tagname = "";
    var count = 0;
    var tags = [];
    var thisHTML = $(this).html();

    $(".tagchoose").click(function() {
        count++;
        if ($.inArray(thisHTML, tags) == -1){
        if (count < 6) {
            $("#tagselectshow").html("Tags Selected: " + count + " tags selected");
            tagname = "<span class='selectedtg'>" + thisHTML + "</span> / ";
            $("#displaythetags").append(tagname);
            tags.push(thisHTML);
        }
        }else{
          alert('Tag already chosen');            
        }
    });
    ....

答案 1 :(得分:0)

选定的类添加到所选元素,然后添加逻辑..

$(document).ready(function(e) {

    var tagname = "";
    var count = 0;

    $(".tagchoose").click(function() {
        var $this = $(this);
        if ($this.hasClass('selected')) {
            $this.removeClass('selected');
        }
        else {
            $this.addClass('selected');
            count++;
            if (count < 6) {
                $("#tagselectshow").html("Tags Selected: " + count + " tags selected");
                tagname = "<span class='selectedtg'>" + $(this).html() + "</span> / ";
                $("#displaythetags").append(tagname);
            }
        }

    });

    $("#deletetags").click(function() {
        count = 0;
        tagname = "";

        $("#tagselectshow").html("Tags Selected: " + count + " tags selected");
        $("#displaythetags").html(tagname);
    });

});​