您e
已将. each
_ e
_ stopPropagation
将e
参数移出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");
}
});