3

这是我的代码,它可以工作,但控制台给了我这个消息:

未捕获的类型错误:对象 2 没有方法“stopPropagation”

这是我的代码:

$(".addtag").click(function () {
    var current_id = $(this).parent().attr("id");
    $('div .tag').each(function (e) {
        var this_tag_id = $(this).attr("id").replace("tag", "");
        if (this_tag_id == current_id) {
            alert("You can't tag an item twice");
            e.stopPropagation();
        }
    });
$("body").css("color","red"); <--- if (this_tag_id == current_id) I want to prevent this from executing.
}

有什么建议么?

4

2 回答 2

4

e已将. each_ e_ stopPropagatione参数移出each函数并进入处理点击的函数。

$(".addtag").click(function(e) {
// Here --------------------^
var current_id = $(this).parent().attr("id");
  $('div .tag').each(function(){
// Not here ------------------^
      var this_tag_id = $(this).attr("id").replace("tag","");
      if (this_tag_id == current_id) {alert("You can't tag an item twice"); e.stopPropagation();}
  });
}

在下面回复您的评论:

$(".addtag").click(function (e) {
    var current_id = $(this).parent().attr("id");
    $('div .tag').each(function () {
        var this_tag_id = $(this).attr("id").replace("tag", "");
        if (this_tag_id == current_id) {
            alert("You can't tag an item twice");
            e.stopPropagation();
        }
    });
    $("body").css("color", "red"); // <-- I want to prevent this from executing if this_tag_id == current_id.
});

在你的 中设置一个标志each,并在之后检查它:

$(".addtag").click(function (e) {
    var current_id = $(this).parent().attr("id");
    var iscurrent = false;       // <=== Flag
    $('div .tag').each(function () {
        var this_tag_id = $(this).attr("id").replace("tag", "");
        if (this_tag_id == current_id) {
            iscurrent = true;    // <=== Set
            e.stopPropagation(); // <=== Put this above alert
            alert("You can't tag an item twice");
        }
    });
    if (!iscurrent) {            // <=== Add check
        $("body").css("color", "red");
    }
});
于 2013-07-26T10:09:22.917 回答
0

如果我明白你的意思:

$(".addtag").click(function (e) {
    e.stopPropagation();
    var current_id = $(this).parent().attr("id");
    $('div .tag').each(function (e) {
        var this_tag_id = $(this).attr("id").replace("tag", "");
        if (this_tag_id == current_id) {
            alert("You can't tag an item twice");
            return false;// will break the each loop here
        }
    });
}
于 2013-07-26T10:17:48.843 回答