如何修复Javascript函数参数(当我使用变量传递参数时)

时间:2018-02-04 01:06:29

标签: javascript html function onclick

<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值。

2 个答案:

答案 0 :(得分:1)

您正在重新分配x变量。

  • 最好的方法是用函数关闭你的逻辑,这样你就可以创建两个名为demodemo2的函数。

请查看此代码段

&#13;
&#13;
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;
&#13;
&#13;

请参阅?现在你的逻辑正在发挥作用!

答案 1 :(得分:0)

或另一种思考方式就是这样......但是,你可能想做Ele做的事情^

&#13;
&#13;
<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;
&#13;
&#13;