Ant*_*ony 5 javascript jquery toggle
当点击"赞"按钮时,我试图在两个函数之间切换.
<div class="like">
<div class="count"><%= post.num_likes %> </div>
<div class="icon" id="like"><i class="icon-thumbs-up-alt"></i></div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在我有:
$(".like").click(function(event){
event.stopPropagation();
$("i", this).toggleClass("icon-thumbs-up-alt").toggleClass("icon icon-thumbs-up");
likePost(TestCanvas, $(this).prev('div').find('.hideThis').text());
});
Run Code Online (Sandbox Code Playgroud)
likePost(canvasID,postID)接受参数并与API交互当我再次单击.like时,我想调用differentPost().
当单击.like时,是否有一种简单的方法可以在likePost()和differentPost()之间切换?
我试过了:
$('.like').toggle(function() {
alert('First handler for .toggle() called.');
likePost(TestCanvas, $(this).prev('div').find('.hideThis').text());
}, function() {
alert('Second handler for .toggle() called.');
unlikePost(TestCanvas, $(this).prev('div').find('.hideThis').text());
});
Run Code Online (Sandbox Code Playgroud)
它没有像我想的那样工作.似乎在页面加载时执行而不是单击.like.
切换课程。通过读取元素是否具有此类,您可以推断出用户喜欢还是删除了它,就像:
$('.like').click(function() {
var val = parseInt($(this).text(), 10);
$(this).toggleClass('is-liked');
if ($(this).hasClass('is-liked')) {
val++
// User has liked (insert userId, itemId into Likes table)
} else {
val--
// User removed his like (delete from table Likes where userId and itemId)
}
$(this).text(val);
});Run Code Online (Sandbox Code Playgroud)
.like {
font: 14px/1.4 sans-serif;
display: inline-block;
padding: 3px 10px;
cursor: pointer;
box-shadow: inset 0 0 0 2px #0bf;
font-weight: bold;
user-select: none;
}
.like:after {
content: "";
vertical-align: top;
margin-left: 5px;
}
.is-liked {
background: #0bf;
color: #fff;
}Run Code Online (Sandbox Code Playgroud)
<span class="like">0</span>
<span class="like is-liked">3</span>
<span class="like">6</span>
<span class="like">12</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>Run Code Online (Sandbox Code Playgroud)