javascript - 更改属性javascript的颜色
问题描述
我目前尝试在 onclick 时更改 div 的颜色但失败,我使用“postid”而不是使用 id 和 class 因为它需要更改仅 onclick 的 div 的颜色
$(function () {
$('.like').click(function () { likeFunction(this); });
});
function likeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=LIKE&PostID=' + postId,
success: function () {}
});
}
<div class="post" postid="10">
<input type="button" class='like' value="LikeButton" /> </input>
</div>
解决方案
你可以$(this)
在你的likeFunction中引用,并使用一个类来改变颜色。
$(function() {
$('.like').click(likeFunction);
});
function likeFunction() {
$(this).addClass('clicked')
var postId = $(this).parent().attr('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=LIKE&PostID=' + postId,
success: function() {}
});
}
.clicked {
background: #f00;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post" postid="10">
<input type="button" class='like' value="LikeButton" /> </input>
</div>
推荐阅读
- python - 如何获取调用者的类定义行号?
- nginx - 不同的 proxy_cache_valid 取决于 nginx 的 request_uri
- go - 无法导入...(不需要模块提供包)
- javascript - 如何通过使用Angular通过属性名称检查属性名称到对象数组来从对象分配值
- c# - Azure Functions C# 如何使用反射将自定义消息从一个类记录到天蓝色监控日志或分析监控日志
- c# - 以编程方式发送电子邮件需要很长时间才能加速?
- python - 在 matplotlib 中绘制组合 3 个变量和重新定位图例的难度
- apache-spark - 如何从数据框中选择聚合列
- python - 使用 Tornado 上传 Excel 文件
- c# - 如何在设计时在控件属性的下拉列表中列出表单上 typeX 组件的所有实例