e.stopPropagation 有效,但在控制台中显示错误
2013-07-26
4863
这是我的代码,它可以运行,但是控制台给出了以下消息:
Uncaught TypeError: Object 2 has no method '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.
}
有什么建议吗?
2个回答
您已将
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");
}
});
T.J. Crowder
2013-07-26
如果我理解你的意思:
$(".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
}
});
}
A. Wolff
2013-07-26