javascript - 如何处理元素的onclick探针中的3倍引号
问题描述
我有一个小问题:在我的项目中,我尝试制作一个like 按钮,并通过onclick proberty 定义了一个附加到函数的按钮。但现在它看起来像这样:
<div class="post-container">
<button class="{% if post.liked %}color-blue{% else %}color-white{% endif %}" id="post_{{ post.id|stringformat:'s' }}" onclick="postLike('{{ post.id|stringformat:'s' }}')"> {{ number_of_likes }} Like{{ number_of_likes|pluralize }}</button>
</div>
Visual Studio Code 将此标记为红色,我不确定如何处理这些,因为当我按下按钮时,我在控制台中的 onclick 上出现错误...
解决方案
像您目前使用的内联处理程序被普遍认为是一种糟糕的做法,原因之一是因为它们在传递字符串参数时存在非常难看的引号转义问题。(它们还需要全球污染,并且有一个疯狂的范围链。)
而是将帖子 ID 放入数据属性中,并将侦听器附加到其他地方独立 JavaScript 中的每个元素。例如,如果您从
<button class="myButton" onclick="postLike('{{ post.id|stringformat:'s' }}')">
改成
<button class="myButton" data-post-id="{{ post.id|stringformat:'s' }}">
并在单击时从按钮中检索帖子 ID。在 HTML 包含所有按钮后,运行以下 JS:
for (const button of document.querySelectorAll('.myButton')) {
button.addEventListener('click', (e) => {
postLike(e.target.dataset.postId);
});
}
您必须.myButton
根据按钮周围的 HTML 标记来调整选择器字符串。
另一种选择,在所有按钮的容器上使用事件委托:
container.addEventListener('click', (e) => {
if (e.target.dataset.postId) {
postLike(e.target.dataset.postId);
}
});
推荐阅读
- kotlin - 为什么大输入的尾递归阶乘输出为零?
- git - 显示在 2 个日期之间合并到 Master 的所有分支 - Git
- firefox - OS/2: Bad sxHeight 设置为 0: -1
- azure-devops - 在自己的 Azure DevOps 服务器安装中使用 https 禁用克隆存储库
- c# - 在 server-ORA-3134 上打开 Oracle 连接时出错
- elasticsearch - ES如何重构一个像join这样的查询?
- excel - Microsoft Word 宏按钮,用于将旧表单数据保存/导出到 Excel 电子表格
- excel - IF(ISNA(MATCH 函数未正确提取数据
- java - Java - calculation distans and distans to origo - issue
- python - How to resample a pandas data frame every half second with data every second?