![](/img/trans.png)
[英]How to check if all the values in jquery array are equal to one specified string?
[英]How to put values of all active buttons into one array with jQuery
这是代表我的问题的小提琴: 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());
});
});
附加说明:
onclick="..."
按钮属性,因为如果您使用jQuery监听click事件,则不需要它。 -
编辑(切换版)
如果您需要在数组中切换按钮值,您只需进行以下编辑:
从:
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
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());
});
}); ]
你需要使用这个指向当前的变量
$(document).ready(function() {
$('button.clicked').click(function() {
alert($(this).text());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.