gpt4 book ai didi

Javascript 将参数传递给函数

转载 作者:行者123 更新时间:2023-11-28 04:35:50 26 4
gpt4 key购买 nike

我尝试将参数传递给函数。当我点击 div 时,它会提醒参数我通过了

我有2个文件

  • index.html
  • 脚本.js

这是我的尝试

示例 1

index.html

<div id="thediv" >

script.js

window.onload = initialize;

//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind

//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
  • 问题是它在没有点击的情况下执行的功能

示例 2

index.html

<div id="thediv" onclick="myfunction('something')" >

script.js

function myFunction(parameter) { alert( parameter ) };
  • 是的,它已经完成了,但是如果我在 index.html 中有很多元素,那么麻烦的是读取哪个元素有哪个监听器会很痛苦
  • 我想将我的代码分成 3 个部分(与示例 1 类似)
    • View (html 元素)
    • 元素有哪个监听器
    • 函数

我该怎么办?或者我可以这样做吗?(我不想使用其他库)

最佳答案

放置 ()(其中包含任意数量的参数)将调用一个函数。然后将返回值(在本例中为 undefined)指定为事件处理程序。

如果要给函数赋值,那么就需要传递函数本身。

...onclick = myFunction;

如果您想在调用时为其提供参数,那么最简单的方法是创建一个新函数并为其赋值。

...onclick = function () {
myFunction("arguments");
};

关于Javascript 将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com