每当单击按钮时,我都会尝试更改数据属性的值和背景颜色,因此在对元素上的事件单击进行 ajax 调用时,它需要考虑多次单击。
到目前为止,背景颜色发生了变化,数据属性发生了变化,但是当第二次单击时,原始data-status
值会在 if 语句中选取,即使它在原始单击中发生了更改。
$(document).ready(function () {
$('.button-create').click(function () {
// assign data from data attributes to variables
var check = $(this).data("value");
var checkID = $(this).data("checkid");
var legend = $(this).data("legend");
var area = $(this).data("area");
var status = $(this).data("status");
// ajaxCall(check, checkID, legend, area, $status)
//change colour when clicked based on status
if($(this).data("status") == 0) {
console.log("Element has been clicked to green");
$(this).css('background', 'green !important');
$(this).attr('data-status','1')
} else if ($(this).data("status") == 1) {
console.log("Element has been clicked to change to red");
$(this).css('background', 'red !important');
$(this).attr('data-status','0')
};
})
})
<html>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<body>
<button class='check-box button-create' data-value='AUDIT' data-checkid='86' data-legend='3' data-area='8' data-status='1' type='submit' name='submit' value='submit'></button>
</body>
</html>
任何帮助都非常感谢! 谢谢
您需要使用.data()
而不是使用.attr()
来设置属性值:
用:
$(this).data('status','0')
而不是:
$(this).attr('data-status','0')