如何在ruby on rails和javascript中使用data-post接收数据


<a class="new_thread" data-post="<%= post.id %>">Button</a>

我试图向Javascript发送数据

$('.new_thread').on('click', async evt => {
evt.preventDefault();
const $tgt = $(evt.target);
const $anchor = $tgt.is('a') ? $tgt : $tgt.parents('a');
const post_id = $anchor.attr('data-post');
const thread = document.getElementById("new_thread_modal_" + post_id);
if (thread.style.display === "none") {
thread.style.display = "block";
} else {
thread.style.display = "none";
}
})

当我点击那个按钮时,javascript文件不工作。我得到了以下错误

Uncaught (in promise) TypeError: Cannot read property 'style' of null
at HTMLAnchorElement.<anonymous> (comments.self-05d964752f9f39ac858194974bab2f9f098c99c773368326d9bde8e452bae945.js?body=1:265)
at HTMLAnchorElement.dispatch (jquery.min.js:3)
at HTMLAnchorElement.r.handle

早些时候,我正在使用onclick,但是,现在我正试图使用data-post发送数据。当我尝试在logcat中打印一些东西时,我注意到我可以得到输出。但是,我如何接收我使用data-post发送的数据?

$('.new_thread').on('click', async evt => {
evt.preventDefault();
const $tgt = $(evt.target);
const post_id = $tgt.attr('data-post');
const thread = document.getElementById("new_thread_modal_" + post_id);
if (thread.style.display === "none") {
thread.style.display = "block";
} else {
thread.style.display = "none";
}
})

这对我很有用。

最新更新