gpt4 book ai didi

jquery - e.stopPropagation 可以工作,但在控制台中出现错误

转载 作者:行者123 更新时间:2023-12-01 01:07:53 24 4
gpt4 key购买 nike

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

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.
}

有什么建议吗?

最佳答案

您已将 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");
}
});

关于jquery - e.stopPropagation 可以工作,但在控制台中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17878598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com