现在我网站的投票系统正在运行,除了当我喜欢某样东西时,它会改变按钮的颜色(通过 jquery/javascript 文件中的 this.* 命令),
但是当我点击相反的按钮 [不喜欢按钮] 时,它会为不喜欢按钮着色并保持喜欢按钮的颜色,有效地让两个按钮都着色直到我刷新页面
.. .
如何抓取被点击元素旁边的按钮元素?
目前我的js代码如下:
$(function() {
$("body").on("click", ".vote", function (event) {
var clicked = $(this);
var request = $.ajax({
url: $(this).attr("href"),
dataType: 'json'
});
event.preventDefault();
request.done(function (data) {
if (data['vote'] == 1 || data['vote'] == -1)
{
clicked.children("button").attr('class', 'btn btn-primary btn-sm');
}
else if (data['vote'] == 0)
{
clicked.children("button").attr('class', 'btn btn-default btn-sm');
}
});
request.fail(function (data) {
alert("Voting failed!");
});
});
});
和我的 View 代码[这些的多个实例,因为有多个带有一对喜欢/不喜欢按钮的框。]:
<!-- Like button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/like/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-up"></span>
</button>
</a>
<!-- Dislike button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/dislike/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-down"></span>
</button>
</a>
最佳答案
在每对投票按钮周围包裹一个 div
<div>
<!-- Like button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/like/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-up"></span>
</button>
</a>
<!-- Dislike button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/dislike/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-down"></span>
</button>
</a>
</div>
然后修改请求完成调用以在为单击的按钮着色之前取消两个按钮的颜色。
request.done(function (data) {
clicked.parent().find('button').attr('class','btn btn-default btn-sm');
if (data['vote'] == 1 || data['vote'] == -1)
{
clicked.children("button").attr('class', 'btn btn-primary btn-sm');
}
});
关于javascript - 如何更改特定按钮,而不使用 jquery 中的 `this` 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23881443/