将this.id的值存储为其他函数的全局变量



如何存储此按钮的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")
}

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

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
}
<button id="1" onclick="myfunction(this.id)">Click Here</button>

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


我想我可以通过展示一种"更好"的方法来帮助你进一步了解这一点。

按钮中的onclick是一个事件侦听器,但实现这一点的首选方法是通过javascript附加侦听器。

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

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

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

此外,传递数字等属性最好通过数据属性来完成,这很酷,因为您可以在这些属性中放入任何信息,并在脚本中轻松获取这些信息。

<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)
}
<button data-id="1" id='theButton'>Click Here</button>

最新更新