javascript - 将按钮 onClick 函数转换为 jQuery

标签 javascript jquery html

目前有 HTML 代码,但希望将其转换为 JavaScript。您可以看到下面的代码:

我想将以下内容转换为 JQuery(而不是 HTML):

<button id="1" onclick="swapStyleSheet('style1.css')">Button1</button>
<button id="2" onclick="swapStyleSheet('style2.css')">Button2</button>
<button id="3" onclick="swapStyleSheet('style3.css')">Button3</button>

上面的代码触发这个:

var swapStyleSheet = function (sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
  storebackground(sheet);
}

var storebackground = function (swapstylesheet) {
  localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}

var loadbackground = function () {
  document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}

window.onload = loadbackground();

谢谢!

最佳答案

你可以尝试这样的事情..

// Here we get all the buttons
var button = document.getElementsByTagName('button');

// We loop the buttons
for (var i=0; i<button.length; i++){

  // Here we add a click event for each buttons
  button[i].onclick = function() {
    alert("style"+this.id+".css");
    //swapStyleSheet("style"+this.id+".css"); you can do it something like that;
  }
}
var swapStyleSheet = function (sheet) {
        //document.getElementById('pagestyle').setAttribute('href', sheet);
        //storebackground(sheet);
    }

var storebackground = function (swapstylesheet) {
       // localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
    }

var loadbackground = function () {
        //document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
    }

//window.onload = loadbackground();
<button id="1">Button1</button>
<button id="2" >Button2</button>
<button id="3" >Button3</button>

不需要JQuery

关于javascript - 将按钮 onClick 函数转换为 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747220/

相关文章:

javascript - 浏览器中 Node 的 net.connect()?

javascript - IF 中的 Typeof 有效,但同一语句的 ELSE 失败

javascript - 使用 jQuery 更改动态创建的输入字段的值

asp.net - 无法在页面上呈现 HTML 输出

html - 使列与具有嵌套框的列相同的高度

html - 如何在 Bootstrap 中创建导航和选项卡样式?

javascript - 使用adobe air和javascript在sqlite db中插入日期

javascript - SapUI5 Popover箭头未​​指向设置offsetY后单击的依赖元素

javascript - 在 Angular Js 中销毁工厂对象

jquery - 如何使用 chrome 重置带有 jquery 的选择框?