javascript 喜欢按钮 - 在两个功能之间切换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17412307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Like button - Toggle between two functions
提问by Anthony
I'm trying to toggle between two functions when a "Like" button is clicked.
单击“喜欢”按钮时,我试图在两个功能之间切换。
<div class="like">
<div class="count"><%= post.num_likes %> </div>
<div class="icon" id="like"><i class="icon-thumbs-up-alt"></i></div>
</div>
right now I have:
现在我有:
$(".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());
});
likePost(canvasID, postID) takes parameters and interacts with an API When I click on .like again, I would like to call unlikePost().
likePost(canvasID, postID) 接受参数并与 API 交互 当我再次点击 .like 时,我想调用不一样的 Post()。
Is there an easy way to toggle between likePost() and unlikePost() when .like is clicked?
单击 .like 时,是否有一种简单的方法可以在 likePost() 和不一样的 Post() 之间切换?
Ive tried:
我试过了:
$('.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());
});
Its not working as i thought it would though. Seems to execute on page load instead of on click of .like.
虽然它不像我想象的那样工作。似乎在页面加载时执行,而不是在点击 .like 时执行。
采纳答案by Roko C. Buljan
Toggle a class. Than by reading if the element has such class - you can deduce if the user liked or removed it's 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);
});
.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;
}
<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>
回答by Smeegs
You can add a "liked" class when liked.
您可以在喜欢时添加“喜欢”的课程。
$('.like').on('click', function() {
if $(this).hasClass("liked") {
//do unlike
$(this).removeClass("liked");
}
else {
//do like
$(this).addClass("liked");
}
});
回答by Alnitak
You can use an element's own data to store the current state of the toggle using $(this).data()
. This will allow many instances of your .like
elements to work independently.
您可以使用元素自己的数据来存储切换的当前状态$(this).data()
。这将允许您的.like
元素的许多实例独立工作。
(Generally speaking I dislike using class
values to represent actual program state. IMHO, classes are for styling, not logic).
(一般来说,我不喜欢使用class
值来表示实际程序状态。恕我直言,类用于样式,而不是逻辑)。
Since your two functions have the same parameters you can also just obtain a reference to the desired function based on the current state and then call it:
由于您的两个函数具有相同的参数,您也可以根据当前状态获取对所需函数的引用,然后调用它:
$(".like").on('click', function(event) {
// from OP's code
event.stopPropagation();
$("i", this).toggleClass("icon-thumbs-up-alt icon icon-thumbs-up");
// extract and toggle state (first click _sets_ state to "truthy")
var data = $(this).data();
data.state ^= 1;
// determine which function to call, then call it - DRY
var fn = data.state ? likePost : unlikePost;
fn(TestCanvas, $(this).prev('div').find('.hideThis').text());
});
回答by chockleyc
回答by prakashapkota
Use one class to find if content was liked or not:
使用一类来查找内容是否被喜欢:
$('.like').on('click', function(evt){
evt.preventDefault();
if( $(this).is('liked') ){
$(this).removeClass('liked');
doUnlike();
}
else{
$(this).addClass('liked');
dolike();
}
}
doUnlike(){
//...
}
dolike(){
//.....
}
回答by Volt
Since toggleClass would be switching in adding and removing class which is kind of work around anyway. And creating a variable is unsuitable for multiple buttons. You can hide a variable in a hidden input tag inside of the div/button and access it with find function. Script will be switching values and it will create wished toggle effect since toggle function does not support two functions anymore and is only used for hide and show.
由于 toggleClass 将在添加和删除类时切换,无论如何这是一种解决方法。并且创建变量不适用于多个按钮。您可以在 div/button 内的隐藏输入标签中隐藏变量,并使用 find 函数访问它。脚本将切换值,它将创建希望的切换效果,因为切换功能不再支持两个功能,仅用于隐藏和显示。
Another possibility:
另一种可能:
<div class="like">
<input type="hidden" value=0 />
One
<div class="display"></div>
</div>
<div class="like">
<input type="hidden" value=0 />
Two
<div class="display"></div>
</div>
<script>
$(".like").click(function() {
var tagvar = "input[type='hidden']";
if ( $(this).find(tagvar).val() == 0 ) {
$(this).find(".display").html("yes");
$(this).find(tagvar).val(1);
}else {
$(this).find(".display").html("no");
$(this).find(tagvar).val(0);
}
});
</script>