如何使用jQuery将所有活动按钮的值放入一个数组中

How to put values of all active buttons into one array with jQuery

本文关键字:数组 一个 jQuery 何使用 按钮 活动      更新时间:2023-09-26

这是代表我的问题的小提琴:https://jsfiddle.net/Ognj3n/jLjh9oLm/基本上,当有人单击任何按钮时onclick函数正在更改按钮的背景颜色,以便用户知道单击了哪个按钮,但我在小提琴中省略了该部分代码。现在我尝试将所有单击按钮的值放入一个数组中,在小提琴中,它应该成为input元素的value。尝试这样做:

$(document).ready(function(){
        $('button.clicked').click(function(){
            var clickedButtons= new Array();
            $('button[background-color="rgb(76, 175, 80)"]').each(function(){
                clickedButtons[clickedButtons.length]=this.value;
            });
        });
    });

但是在$('button[background-color="rgb(76, 175, 80)"]').each(function()内部,没有任何东西是控制台日志记录,就好像那部分代码根本没有解释一样。请帮忙,我被困住了

如果要

在数组中添加按钮值,则每次按下按钮时,都可以按如下方式编辑代码:

每次按下按钮时,我都会调用 push() 函数,该函数将元素值添加到数组中。

法典:

 $(document).ready(function() {
   var clickedButtons = new Array();
   $('button.clicked').click(function() {
     clickedButtons.push(this.value); // adds element to the array
     $(this).unbind('click'); // stop listening 
     console.log(clickedButtons);
     $("here").val(clickedButtons.join());
   });

 });

工作 js小提琴

附加说明:

  • 我从 html 中删除了所有 onclick="..." 按钮属性,因为如果您使用 jQuery 侦听点击事件,则不需要它。

-

编辑(切换版本)

如果您需要切换数组内的按钮值,则只需进行以下编辑:

从:

 clickedButtons.push(this.value); // adds element to the array
 $(this).unbind('click'); // stop listening 

自:

 var index = clickedButtons.indexOf(this.value);
 if (index === -1) 
   clickedButtons.push(this.value);  //value not found so push it
 else
   clickedButtons.splice(index, 1);   // value found so remove it

工作 js小提琴

Below is the working fiddle

  [$(document).ready(function() {
   var clickedButtons = new Array();
 $('button.clicked').click(function() {
  $(this).css('background','red');
     clickedButtons.push( this.value);
    $("#here").val(clickedButtons.join());
  }); 

});]

https://jsfiddle.net/jLjh9oLm/4/

您需要使用此变量哪个点电流

     $(document).ready(function() {
  $('button.clicked').click(function() {
     alert($(this).text());
  });
});