首页 > 解决方案 > 如何处理元素的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 上出现错误...

标签: javascripthtml

解决方案


像您目前使用的内联处理程序被普遍认为是一种糟糕的做法,原因之一是因为它们在传递字符串参数时存在非常难看的引号转义问题。(它们还需要全球污染,并且有一个疯狂的范围链。)

而是将帖子 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);
  }
});

推荐阅读