<p id="demo">Click me.</p>
<p id="demo2">Click me.</p>
<script>
x="demo";
b="ttt";
document.getElementById("demo").onclick = function() {myFunction(x,b)};
x="demo2";
b="555"
document.getElementById("demo2").onclick = function() {myFunction(x,b)};
function myFunction(x,b) {
document.getElementById(x).innerHTML =b ;
}
我的目的是演示,使用onclick函数x =“demo”b =“ttt”;对于演示2,使用onclick函数x =“demo2”和b =“555”。但似乎这两个函数都使用了最新的x和b值。
答案 0 :(得分:1)
x
变量。demo
和demo2
的函数。
let demo = function(x,b) {
document.getElementById("demo").onclick = function() {
myFunction(x, b)
};
};
let x = "demo";
let b = "ttt";
demo(x, b);
let demo2 = function(x,b) {
document.getElementById("demo2").onclick = function() {
myFunction(x, b)
};
};
x = "demo2";
b = "555"
demo2(x, b);
function myFunction(x, b) {
document.getElementById(x).innerHTML = b;
}
&#13;
<p id="demo">Click me.</p>
<p id="demo2">Click me.</p>
&#13;
请参阅?现在你的逻辑正在发挥作用!
答案 1 :(得分:0)
或另一种思考方式就是这样......但是,你可能想做Ele做的事情^
<html>
<button id="demo">Click me.</button>
<button id="demo2">Click me.</button>
<script>
var x = "demo";
var b = "ttt";
document.getElementById("demo").addEventListener(
"click", () => myFunction(x, b)
);
function diffScope() {
var x = "demo2";
var b = "555"
document.getElementById("demo2").addEventListener(
"click", () => myFunction(x, b)
);
}
function myFunction(x, b) {
document.getElementById(x).innerHTML = b
};
// Note: you're initializing that inner function called diffScope
// from above AFTER the first "demo" has already been assigned
// the eventListener
diffScope();
</script>
</html>
&#13;