如何在一个元素的onclick问题中处理3次引号



我有一个小问题:在我的项目中,我试图制作一个类似按钮,并通过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上出现了一个错误。。。

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

将post 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);
});
}

您将不得不根据按钮周围的HTML标记来调整选择器字符串.myButton

另一个选项,在包含所有按钮的容器上使用事件委派:

container.addEventListener('click', (e) => {
if (e.target.dataset.postId) {
postLike(e.target.dataset.postId);
}
});

要处理3次引号,需要在单引号和双引号之间切换。尝试这样做:

onclick='postLike("{{ post.id|stringformat:'s' }}")'

最新更新