首页 > 解决方案 > 如何更改代码来控制某些按钮的名称?

问题描述

有一个代码

$("button").click(function() {
    var btn = this;
    if (btn.loaded) {
      $(btn).prev("div").html(btn.originalContent);
      btn.loaded = false;
      $(btn).text('Get Dynamic chart');
    } else {
      btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
  <h2>Dynamic chart1</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=1">Get Dynamic chart1</button>

<div id="div2">
  <h2>Dynamic chart2</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=2">Get Dynamic chart2</button>

<div id="div3">
  <h2>Dynamic chart3</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=3">Get Dynamic chart3</button>

<div id="div4">
  <h2>Dynamic chart4</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=4">Get Dynamic chart4</button>

<div id="div5">
  <h2>Dynamic chart5</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=5">Another button</button>

所以,Button 5每个人都有不同的名字,但是当你点击它的时候,脚本的名字变成了"Close",这是正常的。但是在点击关闭按钮后,按钮的名称被分配了一个脚本Get Dynamic chart而不是"Another button",即不以原生名称为准。如何确保5th button脚本没有为按下之前和按下之后分配名称,或者如何在脚本中为和分配其5th button名称?谢谢openingclosingreturning to the original name

标签: javascripthtmljquery

解决方案


但是有什么不清楚的呢?

第一次单击它时,它将运行:

   btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }

所以btn.loaded=truetext现在是“关闭”

下次单击时,将运行:

  $(btn).prev("div").html(btn.originalContent);
  btn.loaded = false;
  $(btn).text('Get Dynamic chart');

它完全按照你告诉它去做。

一个更好的问题是......你到底是什么意思?


推荐阅读