我有以下JS / JQ函数来切换用户之间的关注和取消问题。在我的应用中的某些地方,用户可以点击链接文字“关注”或“取消关注”的链接。在其他地方,他们可以点击标有“FOLLOW”或“UNFOLLOW”的按钮。我希望我的this.text()
测试只会更新小写或大写标签,具体取决于我是通过链接还是按钮调用我的函数。但似乎总是执行这两个测试。因此,如果我点击链接文本=“关注”的链接,当我的功能完成时,我最终会得到链接文本=“UNFOLLOW”。有什么建议吗?
$(function () {
$(".question_follow_unfollow").click(function (e) {
e.preventDefault();
if (IS_AUTHENTICATED == 'false') {
window.location = '/login/?next=/';
} else {
$.ajax({
type: "POST",
url: "/question/follow-unfollow/",
data: {
'qid': $(this).data('qid')
},
success: function (e) {
alert('Got it!');
}
});
$(this).text($(this).text() == 'Follow' ? 'Unfollow' : 'Follow');
$(this).text($(this).text() == 'FOLLOW' ? 'UNFOLLOW' : 'FOLLOW');
}
});
});
答案 0 :(得分:3)
如果您的文本全部为大写的区域,我会将其归为样式,因此应使用CSS设置:
.uppercase
{
text-transform:uppercase;
}
然后你就可以做到:
$(this).text($(this).text() == 'Follow' ? 'Unfollow' : 'Follow');
答案 1 :(得分:1)
发生以下情况:
Follow
,因此会更改为Unfollow
Unfollow
不等于FOLLOW
,因此您获得UNFOLLOW
您需要更多检查或更改。
答案 2 :(得分:1)
怎么样:
var arr = {
'Follow': 'Unfollow',
'Unfollow': 'Follow',
'UNFOLLOW': 'FOLLOW',
'FOLLOW': 'UNFOLLOW'
}
$(this).text( arr[ $(this).text() ] );
答案 3 :(得分:0)
如果它可以是多个案例并且您需要保留该案例,那么您将无法使用三元运算符。最容易的就是开关
var theText = $(this).text();
var replacement = "";
switch (theText) {
case : "UNFOLLOW" : replacement = "FOLLOW"; break;
case : "unfollow" : replacement = "follow"; break;
case : "FOLLOW" : replacement = "UNFOLLOW"; break;
case : "follow" : replacement = "unfollow"; break;
}
$(this).text(replacement);