这是我的代码,它有效,但控制台给了我这条消息:
未捕获的TypeError:对象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.
}
有什么建议吗?
答案 0 :(得分:4)
您已将e
声明为each
的参数,而不是事件处理程序的参数,因此e
是DOM元素,而不是事件对象,并且不没有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");
}
});
答案 1 :(得分: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
}
});
}