0

我不明白为什么我的代码不起作用。

我动态创建了三个按钮的组:组的第一个按钮的 id 为 1,第二个为 101,第三个为 201;第二组按钮将分别命名为 2、102 和 202,以此类推。

如果我想通过单击最后一个按钮来删除所有三个按钮,它可以工作。这是我在 onclick 事件中设置的:

butt.onclick = function() {
    removeElement(this.id);
    removeElement(this.id-100);
    removeElement(this.id-200);
}

但是,如果我想通过单击带有此 onclick 事件的中间一个按钮来删除所有三个按钮:

butt.onclick = function() {
    removeElement(this.id+100);
    removeElement(this.id);
    removeElement(this.id-100);
}

它只消除了按钮 1 和 101,但没有消除 201。

似乎它不喜欢“this.id+100”值。什么原因?

提前致谢。

4

3 回答 3

0

尝试 removeElement(parseInt(this.id)+100);

'+' 运算符用于连接,因此需要在加法前进行数字。

于 2012-05-29T13:23:06.883 回答
0

在您的第二个片段中,更改

removeElement(this.id+100);

removeElement(parseInt(this.id)+100);
于 2012-05-29T13:23:11.113 回答
0

您将字符串与数字混合......并使用+字符串连接尝试

butt.onclick = function() {
    removeElement(parseInt(this.id,10)+100);
    removeElement(this.id);
    removeElement(parseInt(this.id,10)-100);
}

您用于parseInt()在 JavaScript 中将字符串转换为数字

于 2012-05-29T13:25:15.223 回答