亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 id 而不是索引來定位按鈕?

如何使用 id 而不是索引來定位按鈕?

慕桂英3389331 2023-10-30 21:12:43
出于維護目的,我只是想使用 ID 而不是索引來更改按鈕的背景顏色。有什么建議如何做到這一點嗎?從 jsfiddle 運行代碼:https ://jsfiddle.net/p6kuf0zv/4/或者查看代碼片段中的代碼:// On click on a button, a popover menu will show up      $("[data-toggle=popover]").popover({        html: true,        sanitize: false,        trigger: 'focus',        content: function() {          return $('#popover-content').html();        }      });      // Creates data items inside local storage with keyName and keyValue      var saveColorPref = (keyName, keyValue) => {        localStorage.setItem(keyName, keyValue);        return keyValue;      }      // Retrieves data items from local storage      var getColorPref = (keyName) => {        return localStorage.getItem(keyName);      }      // How can the code bellow be changed to make use of ID instead of index?      var targetBtn;      function setColor(keyValue) {        var keyName = $(targetBtn).index();        console.log(keyName, keyValue);        $(targetBtn).css("background", saveColorPref(keyName, keyValue));      }      $('.myBtn').each((keyName, item) => {        $(item).click((e) => {          targetBtn = e.target;        });      });.demo1{        background-color: red;      }      .demo2{        background-color: green;      }      .demo3{        background-color: blue;      }<head>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script></head>
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

回應:


如何使用 id 而不是索引來定位按鈕?


更改setColor函數如下圖所示:


前:


function setColor(keyValue) {

  var keyName = $(targetBtn).index();

  console.log(keyName, keyValue);

  $(targetBtn).css("background", saveColorPref(keyName, keyValue));

}

后:


function setColor(keyValue) {

  var keyName = $(targetBtn).attr('id');

  console.log(keyName, keyValue);

  $(targetBtn).css("background", saveColorPref(keyName, keyValue));

}

SO 片段拋出此錯誤:


Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.

所以你看不到按鈕顏色的變化。但這在你的 jsfiddle 中有效。


查看完整回答
反對 回復 2023-10-30
  • 1 回答
  • 0 關注
  • 138 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號