在我更改ID Javascript后,下一个“单击”事件无法工作,问题是什么?
当你有这个:在我更改ID Javascript后,下一个“单击”事件无法工作,问题是什么?,javascript,Javascript,当你有这个: let x = ["1", "3", "5"] $("#button").click( function num() { $("#answers").html(x[0]) document.getElementById("button").setAttribute("id", "button2"); } ) $("#button2").click( function num2() { $("#answers").html(x[1])
let x = ["1", "3", "5"]
$("#button").click(
function num() {
$("#answers").html(x[0])
document.getElementById("button").setAttribute("id", "button2");
}
)
$("#button2").click(
function num2() {
$("#answers").html(x[1])
document.getElementById("button").setAttribute("id", "button3");
}
)
$("#button3").click(
function num3() {
$("#answers").html(x[2])
}
)
。。。这将着眼于按钮2现在,而不是在未来的一些重命名。因为一开始没有这样的id,所以这个.click方法没有任何作用
你可以用,但在你的情况下,我会去一个不同的解决方案
更改DOM元素的id属性是非常糟糕的做法。取而代之的是使用一个变量,它将决定您在哪种情况下使用该变量,并且只需在您检查该变量的地方使用一键式处理程序。大概是这样的:
$("#button2").click(.......
如果逻辑非常简单,您只想显示x数组中的下一个条目,那么让状态为该索引:
var state = 1;
$("#button").click(function num() {
if (state == 1) {
$("#answers").html(x[0]);
state = 2; // move to the next state..
} else if (state == 2) {
// do something else...
state = 3;
} else if (state == 3) {
// ... etc ...
}
})
当你有这个:
let x = ["1", "3", "5"]
$("#button").click(
function num() {
$("#answers").html(x[0])
document.getElementById("button").setAttribute("id", "button2");
}
)
$("#button2").click(
function num2() {
$("#answers").html(x[1])
document.getElementById("button").setAttribute("id", "button3");
}
)
$("#button3").click(
function num3() {
$("#answers").html(x[2])
}
)
。。。这将着眼于按钮2现在,而不是在未来的一些重命名。因为一开始没有这样的id,所以这个.click方法没有任何作用
你可以用,但在你的情况下,我会去一个不同的解决方案
更改DOM元素的id属性是非常糟糕的做法。取而代之的是使用一个变量,它将决定您在哪种情况下使用该变量,并且只需在您检查该变量的地方使用一键式处理程序。大概是这样的:
$("#button2").click(.......
如果逻辑非常简单,您只想显示x数组中的下一个条目,那么让状态为该索引:
var state = 1;
$("#button").click(function num() {
if (state == 1) {
$("#answers").html(x[0]);
state = 2; // move to the next state..
} else if (state == 2) {
// do something else...
state = 3;
} else if (state == 3) {
// ... etc ...
}
})
只需添加当前索引,您的代码就会很简单:
var index = 0;
$("#button").click(function num() {
$("#answers").html(x[index]);
index = (index+1) % x.length; // round robin selection of array value
})
请参见游乐场:只需添加当前索引,您的代码将非常简单:
var index = 0;
$("#button").click(function num() {
$("#answers").html(x[index]);
index = (index+1) % x.length; // round robin selection of array value
})
请参见游乐场中的:请正确缩进以使其可读。$button2。单击…在当前具有id button2的元素上安装事件侦听器。如果不存在这样的元素,则不会安装事件侦听器。之后更改ID没有帮助,您的按钮仍然是相同的元素,并且附加了原始侦听器。在单击方法之后还需要分号。单击。。。;不要使用三个不同的侦听器,而是使用一个状态变量来存储要在html中使用的x值的索引。@Ifaruki分号是可选的。在这里,如果没有,它可以正常工作。请将其正确缩进以使其可读。$button2。单击…在当前具有id button2的元素上安装事件侦听器。如果不存在这样的元素,则不会安装事件侦听器。之后更改ID没有帮助,您的按钮仍然是相同的元素,并且附加了原始侦听器。在单击方法之后还需要分号。单击。。。;不要使用三个不同的侦听器,而是使用一个状态变量来存储要在html中使用的x值的索引。@Ifaruki分号是可选的。在这里,它可以正常工作。