【发布时间】:2014-01-30 05:21:55
【问题描述】:
如果按钮文本被“关注”并且用户将鼠标悬停在它上面,我希望文本更改为“取消关注”,并在用户停止悬停后改回“关注”。
按钮:
{%if follow%}
<button type="submit" id="status" class="button" value="True"><span>followed</span></button>
{%else%}
<button type="submit" id="status" class="button" value="False"><span>follow</span></button>
{%endif%}
jQuery:
<script>
$(document).ready(function(){
$(".button").click(function() {
var status = $("#status").val();
var course = $("#course").html()
//SECTION THAT I'M HAVING TROUBLE WITH
if ($(".button span").html() == "followed") {
$(".button").mouseover(function() {
$(".button span").html() = "unfollow";
}
}
$.ajax({
type: "POST",
url: "/follow",
data: 'status=' + status + "&course=" + course,
success: function() {
$(".button span").html($(".button span").html() == 'followed' ? 'follow' : 'followed');
$(".button").val($(".button").val() == 'True' ? 'False' : 'True');
}
});
return false;
});
});
</script>
当我运行它时,我得到了
405 Method Not Allowed
The method POST is not allowed for this resource.
但是当我删除鼠标悬停代码时它可以工作。鼠标悬停代码有什么问题?
编辑: 更新了 jQuery,现在可以在 onclick 代码之外使用 mouseout:
if ($(".button span").html() == "followed") {
$(".button").mouseover(function() {
$(".button span").html("unfollow");
});
$(".button").mouseout(function() {
$(".button span").html("followed");
});
}
编辑: 实际上,使用上面的代码,如果按钮被“关注”并且我点击它,按钮文本仍然是“关注”。我认为这是因为 mouseout 函数覆盖了将其更改为“跟随”的 ajax 成功函数。单击按钮后如何覆盖“跟随”鼠标移出功能?
【问题讨论】:
-
$(".button span").html("unfollow");不要分配给html(),传递一个字符串。不确定这是否是您唯一的问题 - 405 错误似乎无关。也许它只响应 GET? -
我认为远程资源不允许发布请求
-
远程资源问题是因为您从 FOLDER 获得响应,而不是 PHP 文件...
标签: javascript jquery