【问题标题】:Store value of this.id as global variable for other functions将 this.id 的值存储为其他函数的全局变量
【发布时间】:2021-09-04 16:38:59
【问题描述】:

如何存储此按钮的 ID 值,以便在其他无法点击的功能上使用它?

<button id="1" onclick="myfunction(this.id)">Click Here</button>

function myfunction(clicked){
var thisnum = clicked;
document.querySelector(".holder--" + thisnum).classlist.add("store")
}

function secondfunction(){
document.querySelector(".box--" + thisnum).classlist.remove("store")
}

【问题讨论】:

  • a) varmyfunction 内,它不是全局的 b) 你在哪里调用 secondfunction

标签: javascript function variables


【解决方案1】:

您可以在函数外部启动变量,并从函数内部给它们一个值,如下所示:

var thisnum; // Initiate the variable globally

function myfunction(clicked){
  thisnum = clicked; // And now change its value
  secondfunction();
}

function secondfunction(){
  console.log("Here is the id: " + thisnum); // And now read its value
}
&lt;button id="1" onclick="myfunction(this.id)"&gt;Click Here&lt;/button&gt;

【讨论】:

    【解决方案2】:

    您的代码可以正常工作并传递元素 ID,但要回答您的问题 - 您需要在任何函数之外初始化变量。然后,当您设置它时(在函数中或其他地方),它将可用于脚本中的其他函数。


    我想我可以通过展示一个“更好”的方式来帮助你进一步了解这个问题。

    按钮中的onclick 是一个事件监听器,但最好的方法是通过javascript 附加监听器。

    document.querySelector('#theButton').addEventListener('click', myfunction);
    

    你会注意到我把它放在下面的window.onload 函数中。这是因为我们不想在所有 HTML 有机会进入页面(页面加载后)之前尝试设置监听器。

    此侦听器函数自动传递一个函数参数event,您可以将其命名为任何名称(您通常将其视为e)。对创建此事件的对象(按钮)的引用始终为 e.target

    最好通过data-attributes 传递数字等属性,这很酷,因为您可以将任何信息放入其中并轻松地在脚本中提取它们。

      <button data-id="1" id='theButton'>Click Here</button>
      <!-- notice the data-id attribute -->
    
      // and in your script:
      var thisnum = e.target.dataset.id
    

    另外,虽然从技术上讲,您可以对元素执行 id='1' 之类的操作,但这不是一个好习惯。最好使用显式字符串(或至少以字母开头)。

    window.onload = function() {
      document.querySelector('#theButton').addEventListener('click', myfunction);
    }
    
    let id // define the variable outside of the functions
    
    function myfunction(e) {
      id = e.target.dataset.id // set the variable wherever
      console.log('the ID:', id);
      
      setTimeout(() => {otherfunction()}, 1000);
    }
    
    function otherfunction() {
    console.log("ID from otherfunction: ", id)
    }
    &lt;button data-id="1" id='theButton'&gt;Click Here&lt;/button&gt;

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多