【问题标题】:Changing multiple button color separately when clicked单击时分别更改多个按钮颜色
【发布时间】:2019-01-16 21:47:03
【问题描述】:

我的 javascript 代码有问题,我有一个 sn-p,它根据循环范围创建多个按钮,这些按钮共享相同的类但 ID 不同

<div class="panel-footer" id="loop">
    <ul class="post-action">
         {% for i in range %}
                <button class="btn btn-success guess" id="{{ i }}" value="{{ i }}" onclick="transferField(this.value)">{{ i }} </button>
         {% endfor %}
    </ul>
</div>

我试图在单击每个按钮时更改它的颜色,再次单击时会更改回默认颜色,但它不能正常工作,当我单击按钮 5 时它会更改颜色,但是一旦我单击按钮 6,它在我单击按钮 6 或再次单击另一个按钮之前不会改变颜色。这是js代码:

<script>

        clicked = true;

        $(".guess").click(function(){
            xyz = this.id
            console.log(xyz)
            if(clicked){
                $('#' + this.id).css('background-color', '#FF8E2B');
                clicked  = false;
            } else {
                $('#' + this.id).css('background-color', '#27AE60');
                clicked  = true;
            }
        });


</script>

我做错了什么?

【问题讨论】:

  • fyi,$('#' + this.id) 只是 $(this) ...其次,您有一个布尔值 clicked,您试图用它来“存储”多个按钮的状态 - 一个布尔值一键:p
  • 而不是获取 id 并使用它,而是使用这个上下文,如 $(this)
  • @guradio 你不认为点击按钮transferField() 不会调用他编写的点击代码吗?
  • @guradio 你的意思是这个 clicked = true; $(".guess").click(function(){ console.log(this) if(clicked){ $(this).css('background-color', '#FF8E2B'); clicked = false; } else { $(this).css('background-color', '#27AE60'); clicked = true; } });即使这仍然没有单独更改按钮背景
  • @AlivetoDie transferField() 做了其他事情,与问题无关

标签: javascript jquery


【解决方案1】:

您的问题是您使用clicked 作为全局变量。

只需将clicked 存储在this 中即可。

   

        $(".guess").click(function(){
            xyz = this.id
            console.log(xyz)
            if(this.clicked){
                $(this).css('background-color', '#FF8E2B');
                this.clicked  = false;
            } else {
                $(this).css('background-color', '#27AE60');
                this.clicked  = true;
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-footer" id="loop">
    <ul class="post-action">
         
                <button class="btn btn-success guess" id="one" value="one" > one</button>
                <button class="btn btn-success guess" id="two" value="two" > two</button>
                <button class="btn btn-success guess" id="three" value="three" > three</button>
         
    </ul>
</div>

【讨论】:

  • 谢谢哥们。我试试看
【解决方案2】:

您正在尝试使用单个 var 来“跟踪”多个按钮的状态,这当然行不通

改用以下方法

$(".guess").click(function(){
    var $this = $(this);
    var clicked = $this.data('clicked');
    if(clicked) {
        $this.css('background-color', '#FF8E2B');
    } else {
        $this.css('background-color', '#27AE60');
    }
    $this.data('clicked', !clicked);
});

【讨论】:

  • 没关系,我错过了删除一行 - 如果逻辑仍然错误,请尝试 if (!clicked) { 而不是 if (clicked) {
【解决方案3】:

您可以将每个元素的颜色数组存储在元素的data-*,使用.data()Array.prototype.reverse() 切换到数组,将background 设置为数组索引0 处的元素

$("button").on("click", function() {
  $(this).css("background", $(this).data().colors.reverse()[0])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-colors='["#FF8E2B", "#27AE60"]' style="background:#FF8E2B">click</button>

【讨论】:

  • 这里设置了background。您是否将$("button").on("click", function(){}) 放在.ready() 处理程序中?
【解决方案4】:

我做错了什么?

您的代码的主要问题是您有 一个 变量来跟踪 多个 按钮元素的点击状态。

解决这个问题的方法是为元素本身添加状态本质上为多个元素提供多个变量。

我通过将event 对象添加到click 处理程序的回调并获取event.currentTarget 来做到这一点。 event.currentTarget 的值是被点击的元素对象。您可以向该对象添加状态,就像向另一个其他 javascript 对象添加状态一样

event.currentTarget.clicked = true;

现在您可以跟踪每个元素的状态!

// just some simple code to get your template in pure JS, don't worry about the code here
const range = [0,1,2,3,4,5];

const template = `<div class="panel-footer" id="loop">
  <ul class="post-action">
    ${range.map(i => `
      <button class="btn btn-success guess" id="${i}" value="${i}">${i}</button>
    `)}
  </ul>
</div>`;

const div = document.createElement('div');
div.innerHTML = template;
document.body.appendChild(div);

// here are where the changes start

// var clicked = true; instead of having a global variable to keep track of the state of all your buttons

$(".guess").click(function(event) {
  // you need local state attached to the button
  
  // here we're getting the button element being clicked
  const currentTarget = event.currentTarget;
  xyz = this.id
  console.log(xyz);
  
  // if clicked is truthy
  if (currentTarget.clicked) {
    $('#' + this.id).css('background-color', '#FF8E2B');
    currentTarget.clicked = false;
  } else {
    $('#' + this.id).css('background-color', '#27AE60');
    // set on the element some state
    currentTarget.clicked = true;
  }
});
.guess {
  /* start out in the orange state */
  background-color: #FF8E2B;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多