2

我的代码使用户最多可以选择 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); 
    });

});

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

4

2 回答 2

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');            
        }
    });
    ....
于 2012-11-05T18:24:31.670 回答
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);
    });

});​
于 2012-11-05T18:16:19.460 回答