首页 > 解决方案 > 更改属性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>

标签: javascripthtmljquerycss

解决方案


你可以$(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>


推荐阅读