简体   繁体   English

使用“onclick” function 调用修改 Javascript 中的变量

[英]Using an "onclick" function call to modify a variable in Javascript

Can someone tell me where I'm going wrong here?有人可以告诉我我哪里出错了吗? I want the functionality of the first piece of code to work with an "onclick" function call.我希望第一段代码的功能与“onclick”function 调用一起使用。

<html>
    <body>
        <h1>Global variables</h1> 
        <p id="before">Something should print here</p>
        <p id="after">Something should print here</p>

    <script>
        x = 0;
        document.getElementById("before").innerHTML = x;
        day();
        function day() {
        x = 5;
        }
        document.getElementById("after").innerHTML = x;
    </script>
    </body>
</html>

I can't get this to work properly.我无法让它正常工作。 According to w3schools: "If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable".根据 w3schools 的说法:“如果你给一个没有声明的变量赋值,它会自动成为一个 GLOBAL 变量”。

<html>
    <body>
        <h1>Global variables</h1> 
        <div id="buttons">
            <button id="5" onclick=day(this.id)>Click me to find out the ID!</button>
        </div>
        <p id="test">Something should print here</p>

    <script>
        function day(id) {
            x = id;
        }
        document.getElementById("test").innerHTML = x;
    </script>
    </body>
</html>

This modified w3schools code demonstrates my problem:这个修改后的 w3schools 代码演示了我的问题:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Scope</h2>

<p>carName within myFunction() and outside myFunction are distinct.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
carName = "Toyota";
myFunction();

function myFunction() {
  var carName = "Volvo";
  document.getElementById("demo1").innerHTML = "This variable - " + carName + " is defined within the function";
}
document.getElementById("demo2").innerHTML = "This variable - " + carName + " is defined outside the function";
</script>

</body>
</html>

You need to move the innerHTML assignment into the day() function.您需要将innerHTML赋值移动到day() function 中。

<script>
   var x;
   function day(id) {
   x = id;
}
document.getElementById("test").innerHTML = x;
</script>

It is generally not a good idea to use inline event handling ( onclick=... within html).使用内联事件处理( onclick=...在 html 中)通常不是一个好主意

You can use an event handler for the button that prints the value of the button id.您可以为打印按钮 ID 值的按钮使用事件处理程序。 See also...也可以看看...

Something like:就像是:

 let id4, id5, id6; // It may be better to lessen 'pollution of the global scope' // eg by assigning the value to properties of one object // https://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted let myVariables = { id4: null, id5: null, id6: null }; // add event listener document.addEventListener("click", clickHandling); function clickHandling(evt) { // ^ event is sent automatically on event occurence const origin = evt.target; // ^ evt.target returns the element the event originated from if (origin.nodeName === "BUTTON") { // ^ only do stuff when the origin is a button const numericId = Number(origin.id.replace(/[^\d]/g, "")); // ^ retrieve only numeric value(s) from id window[`id${numericId}`] = +numericId; // ^ a global variable is actually a property of 'window', // so, you can assign a value to that myVariables[`id${numericId}`] = +numericId; // ^ same, but now use 'myVariables' object console.clear(); console.log(`id${numericId} = ${ window[`id${numericId}`]} and myVariables.id${numericId} = ${ myVariables[`id${numericId}`]}`); // ^ show the assigned values in the console document.querySelector("#test").textContent = `My id is ${origin.id}`; // ^ print button id value to p#test } }
 <div id="buttons"> <button id="b_4">Click me to find out the ID!</button><br> <button id="b_5">Click me to find out the ID!</button><br> <button id="b_6">Click me to find out the ID!</button> </div> <p id="test">Something should print here</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM