0

我见过类似的问题,但似乎没有一个能满足我的需求。我需要根据列表禁用按钮。这是我的代码:

<button id="obj1" disabled>OBJ1</button>
<button id="obj2">OBJ2</button>
<button id="obj4" disabled>OBJ4</button>
<button id="obj5" disabled>OBJ5</button>
<button id="obj7">OBJ7</button>
<button id="obj8">OBJ8</button>

<script>
card_1_buttonList = new Array();
card_1_buttonList[0] = "1";
card_1_buttonList[1] = "2";
card_1_buttonList[2] = "4";

card_2_buttonList = new Array();
card_2_buttonList[0] = "5";
card_2_buttonList[1] = "7";
card_2_buttonList[2] = "8";

var CURRENTCARD = 2;
var BUTTONCOUNTER = 1;


var buttonDisabled = document.getElementById('obj' + card_CURRENTCARD_buttonList[BUTTONCOUNTER]).disabled;

alert(buttonDisabled);
</script>

如何在不修改现有数组的情况下做到这一点?

jsFiddle 示例

4

3 回答 3

1
var CURRENTCARD = 2;
var BUTTONCOUNTER = 7;
var buttonDisabled = document.getElementById('obj' + card_CURRENTCARD_buttonList[BUTTONCOUNTER]).disabled;
alert(buttonDisabled);

问题出在这段代码的第三行。你的名字是错误的。首先尝试制作数组名称。

var cardArr = "card_" + CURRENTCARD + "_buttonList" ; // this will give you array name. like card_1_buttonList

var buttonDisabled = document.getElementById('obj' + window[cardArr]BUTTONCOUNTER]).disabled;

我认为这会奏效。

于 2013-10-18T17:42:51.477 回答
1

尝试这个:

card_1_buttonList = new Array();
card_1_buttonList[0] = "1";
card_1_buttonList[1] = "2";
card_1_buttonList[2] = "4";

card_2_buttonList = new Array();
card_2_buttonList[0] = "5";
card_2_buttonList[1] = "7";
card_2_buttonList[2] = "8";

var CURRENTCARD = 2;
var BUTTONCOUNTER = 2;

var buttonDisabled = document.getElementById('obj' + window['card_' + CURRENTCARD + '_buttonList'][BUTTONCOUNTER]).disabled;

alert(buttonDisabled);

小提琴:http: //jsfiddle.net/Seawd/

另外,请注意 BUTTONCOUNTER 是数组索引,因此 7 (正如您所拥有的那样)不是它的有效值。如果您希望计数器成为值而不是索引,则需要进行额外的处理来获取索引。

于 2013-10-18T17:31:02.047 回答
1

你不能那样做。相反,您可以创建一个具有以下结构的二维数组

var card_buttonList = [];

card_buttonList[0] = new Array();
card_buttonList[0][0] = "1";
card_buttonList[0][1] = "2";
card_buttonList[0][2] = "4";

card_buttonList[1] = new Array();
card_buttonList[1][0] = "5";
card_buttonList[1][1] = "7";
card_buttonList[1][2] = "8";

使用这种结构,您将能够使用这样的索引

var CURRENTCARD = 2;
var BUTTONCOUNTER = 7;

var buttonDisabled = document.getElementById('obj' + 
   card_buttonList[CURRENTCARD ][BUTTONCOUNTER]).disabled;
于 2013-10-18T17:25:00.527 回答