Jquery-切换按钮类和操作

Jquery - Toggle button class and action

本文关键字:操作 按钮 Jquery-      更新时间:2024-02-06

我想在不刷新页面的情况下创建切换按钮onclick编写本地存储并动态切换类。它在某种程度上就像一个复选框。这是代码:

....
document.write("<button id='wawa_"+i+"'");
   if (!checked) {
   document.write("class='buttons uncheck' onClick='clickYes("+i+")'");
   } else {
    document.write("class='buttons check' onClick='clickNo("+i+")'");   
   }
   document.write(">cek</button>");
   document.write("</td></tr>");

  }
  document.write("</table>");
    function clickYes(x) {
    window.localStorage.setItem("selected"+x, x);   
    alert("yeaaaahhh"); }

    function clickNo(x) {
    window.localStorage.removeItem("selected"+x);
    alert("noooo");
    }

使用此代码,它不能在运行中更改数据已保存,但如果要删除数据,则必须刷新页面(因为按钮操作不会更改)我正在开发一个调度程序应用程序。

尝试使用DOM元素,而不是将HTML写入文档
而且尽量不要将值"硬编码"为参数:(

相反,你可以。。。

...
for (var i = 0; i < n; i++) {
    var btn = document.createElement('button');
    btn.className = 'buttons uncheck';
    btn.setAttribute('data-index', i);
    btn.setAttribute('data-checked', false);
    btn.onclick = function() {clickAction()}
    document.getElementById('your-table-id').append(btn);
}
function clickAction() {
    var x = this.getAttribute('data-index');
    if (this.getAttribute('data-checked') == 'false') {
        localStorage.setItem("selected" + x, x);
        btn.setAttribute('data-checked', true);
        this.className = 'buttons check';
        alert("noooo");
    } else {
        localStorage.removeItem("selected" + x);
        btn.setAttribute('data-checked', false);
        this.className = 'buttons uncheck';
        alert("yeeeees");
    }
}

我认为这应该有效,这不是你能得到的最好的代码,但试着理解如何使用DOM,然后当你理解它时,试着使用JQuery或Zepto,这些会对你有很大帮助。

请检查https://developer.mozilla.org/en-US/docs/DOM了解更多信息。