【发布时间】:2021-05-09 04:13:01
【问题描述】:
是的,我已经阅读了许多其他有相同问题的帖子,但我不明白如何解决这个问题。我创建了一个书签按钮,它需要在点击时更改图标。
我的 jQuery:
jQuery(document).ready( function() {
var bm = jQuery(".user_bookmark");
bm.on("click", ".user_bookmark", function (e) {
e.preventDefault();
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : bookmarkAjax.ajaxurl,
data : {action: "eri_user_bookmark", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
var add = 'Add Bookmark';
var remove = 'Remove Bookmark';
var display = bm.attr('display');
var bookmarked = bm.attr('bookmarked');
if (display == 'icon') {
add = '<i class="x-icon" data-x-icon-o="" aria-hidden="true"></i>';
remove = '<i class="x-icon" data-x-icon-s="" aria-hidden="true"></i>';
}
if (bookmarked) {
bm.html(remove);
bm.attr('bookmarked', 'false');
} else {
bm.html(add);
bm.attr('bookmarked', 'true');
}
}
else {
alert("Your bookmark could not be added")
}
}
})
});
})
一开始我有bm.click(),但它只需要单击一下,然后我阅读切换到.on()功能,现在它正在刷新页面。
我尝试将function (e) 替换为function (),并将e.preventDefault(); 替换为return false;、e.stopImmediatePropagation(); 和e.stopPropagation();。
还尝试使用所有这些变体将bm.on() 与jQuery(document).on() 切换。那仍然运行我的代码并且没有刷新,但它没有更改 jQuery 代码中的元素。
示例 HTML:
<a class="user_bookmark" data-nonce="2b92b05de9" data-post_id="1" href="https://example.com/wp-admin/admin-ajax.php?action=eri_user_bookmark&post_id=1&nonce=2b92b05de9" display="icon" bookmarked="true" style="outline: none;">
<i class="x-icon" data-x-icon-s="" aria-hidden="true"></i>
</a>
完整的 PHP 要点:https://gist.github.com/mrgandy/91361fca86e769235eec684a4647b875
【问题讨论】:
-
你有嵌套的
.user_bookmark元素吗?如果不是,那么问题在于您如何附加事件处理程序,而不是preventDefault。 -
@RoryMcCrossan,我不确定你的意思。如果您不介意快速浏览一下,我在上面添加了我的完整代码?
标签: javascript jquery onclick click refresh