1
<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 ;
}

My intent is for demo, use onclick function with x="demo" b="ttt"; and for demo 2, use onclick function with x="demo2" and b="555". but seems both functions used most updated x and b values.

0

2 Answers 2

1

You're re-assigning x variable.

  • The best approach is close your logic with functions, so you can create two functions called demo and demo2.

Look at this code snippet

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;
}
<p id="demo">Click me.</p>
<p id="demo2">Click me.</p>

See? now your logic is working!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But if there are hundreds of x and b... is creating hundreds of onclick function the only option? I was thinking to do that using a loop and use one function and pass x,b through that function's argument.but seems that function always uses the most updated value of x/b (not the x/b value when document.getelement("demo").onclick=funcion happens).
0

or another way to think about it is like this... but yeah, you probably want to do what Ele did ^

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.