There is a thumb-up button on each message bubble of the chatbot. As there are multiple bubbles on each page, both the text bubble and the thumb-up button are indexed. I am attempting to delegate the event from a higher level of the DOM, but the toggleClass doesn't work properly here. The button switched to thumb-up-black on the first click but it freezes on the second click. I wonder why
聊天机器人的每个消息气泡上都有一个竖起大拇指的按钮。由于每个页面上有多个气泡,因此文本气泡和拇指向上按钮都被索引。我试图从DOM的更高级别委托事件,但是toggleClass在这里不能正常工作。按钮在第一次点击时切换到拇指向上-黑色,但在第二次点击时冻结。我想知道为什么
let rating_dict = { "ratingUp": {}};
$(document).on("click", ".thumbup", function() {
const buttonid = $(this).data("index");
$(this).toggleClass("thumbup thumb-up-black");
rating_dict.ratingUp[buttonid] = !rating_dict.ratingUp[buttonid];
});
<div class="rating-img">
<button type="submit" class="thumbup" data-index="${message_index}""></button>
<button type="submit" class="thumbDown" data-index="${message_index}"></button>
</div>
更多回答
Your code takes the "thumbup" class away, so the event handler won't fire.
您的代码去掉了“Thumbup”类,所以事件处理程序不会触发。
优秀答案推荐
The issue here is that you're trying to toggle between two classes, but you're using the same class to select the element. When you click the button for the first time, the class "thumbup" is removed and "thumb-up-black" is added. So, when you try to click it again, there's no element with the class "thumbup" to select and the function doesn't get triggered.
这里的问题是,您试图在两个类之间切换,但您使用同一个类来选择元素。当您第一次点击该按钮时,类“Thumbup”被移除,而被添加的是“拇指向上黑色”。因此,当您再次尝试单击它时,没有带有“Thumbup”类的元素可供选择,函数也不会被触发。
You can solve this by using a common class for selection and separate classes for toggling. Here's how you can do it:
可以通过使用用于选择的公共类和用于切换的单独类来解决此问题。以下是你如何做到这一点:
let rating_dict = { "ratingUp": {}};
$(document).on("click", ".thumb", function() {
const buttonid = $(this).data("index");
$(this).toggleClass("thumbup thumb-up-black");
rating_dict.ratingUp[buttonid] = !rating_dict.ratingUp[buttonid];
});
And your HTML:
和您的Html:
<div class="rating-img">
<button type="submit" class="thumb thumbup" data-index="${message_index}"></button>
<button type="submit" class="thumb thumbDown" data-index="${message_index}"></button>
</div>
In this way, the "thumb" class is used to select the element and the "thumbup" and "thumb-up-black" classes are toggled on click.
通过这种方式,“Thumb”类被用来选择元素,而“Thumbup”和“Thumb-up-Black”类在点击时被切换。
更多回答
Or simply not turn off the "thumbup" class.
或者干脆不关掉“Thumbup”课程。
我是一名优秀的程序员,十分优秀!