使用下面的脚本,我用一些ajax添加和删除了最喜欢的文章,除了一个小细节之外,一切都进行得很顺利。如果我单击.save-audition元素,行为的一部分就是添加类.fa-check (它覆盖一个复选标记,指示已保存了post )。
然后,当悬停时,复选标记(如脚本末尾所示)接受类.fa-close (它将复选标记转换为X),这样用户就可以单击并从他们的收藏夹中删除帖子。
但是,当动态生成复选标记类时,悬停效果就不起作用了,而且我也不知道如何修复它。
jQuery(document).ready( function($) {
$('.save-audition').on('click', function() {
var post_id = $(this).attr("data-post_id")
var nonce = $(this).attr("data-nonce")
var clicked = $(this);
$.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl, //we can use this value because in our php file we used wp_localize_script
data : {action: "tps_save_audition", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
clicked.children('span').children('.fa-stack-2x').addClass('fa-check');
clicked.children('span').children('.fa-stack-1x').addClass('saved');
} else if (response.type = "removed") {
clicked.children('span').children('.fa-stack-2x').removeClass('fa-check');
clicked.children('span').children('.fa-stack-1x').removeClass('saved');
} else {
alert(response.message);
}
}
})
return false;
});
$('.actions .fa-check').hover(function(){
$(this).addClass('fa-close');
$(this).removeClass('fa-check');
$(this).attr('title', 'Remove from saved');
$(this).css('color', '#ff0000');
}, function(){
$(this).removeClass("fa-close");
$(this).addClass('fa-check');
$(this).attr('title', 'Save audition');
$(this).css('color', '#00e20b');
});
})腐蚀PHP/的片段
$saved = get_user_meta(get_current_user_id(), 'saved_auditions', true);
if (in_array($post->ID, $saved)) {
$checkClass = 'fa-check';
$savedClass = 'saved';
} else {
$checkClass = '';
$savedClass = '';
}?>
<a class="save-audition" data-nonce="<?php echo $nonce; ?>" data-post_id="<?php echo $post->ID; ?>" href="<?php echo $link; ?>">
<span class="fa-stack">
<i class="fa fa-save <?php echo $savedClass; ?> fa-stack-1x" title="Save Audition"></i>
<i class="fa <?php echo $checkClass; ?> fa-stack-2x" title="Save Audition"></i>
</span>
</a>发布于 2016-05-01 23:59:12
这是因为悬停事件侦听器是在动态添加元素之前绑定的。您应该尝试侦听mouseover/mouseout事件,该事件冒泡到最近的静态元素(.on('hover') for jQuery)或document元素:
$(document)
.on('mouseover', '.actions .fa-check', function() {
$(this).addClass('fa-close');
$(this).removeClass('fa-check');
$(this).attr('title', 'Remove from saved');
$(this).css('color', '#ff0000');
})
.on('mouseout', '.actions .fa-close', function() {
$(this).removeClass("fa-close");
$(this).addClass('fa-check');
$(this).attr('title', 'Save audition');
$(this).css('color', '#00e20b');
});https://stackoverflow.com/questions/36973326
复制相似问题