You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在script标签中传递函数作为参数并触发执行?

如何将函数作为参数传递给script标签并触发

你原来的写法存在问题,data-myfunc={myfunction()}这种格式无法被正确识别,正确的思路是通过data属性传递函数名称字符串,再在引入的脚本中从全局作用域找到对应函数并调用。

1. 调整HTML结构

首先把函数定义放在widget脚本之前(确保函数在widget执行时已存在),同时给script标签的data属性传入函数名:

<script>
function myfunction() {
    console.log("hello world");
}
</script>
<script src="http://path/to/widget.js?param_a=1&param_b=3" data-myfunc="myfunction"></script>

2. 在widget.js中实现函数调用

在widget.js里,我们可以通过document.currentScript获取当前加载的script标签,再提取data属性里的函数名,最后调用全局函数:

// widget.js 核心代码
// 获取当前正在执行的script标签
const currentScript = document.currentScript;
// 读取data-myfunc属性的函数名
const targetFuncName = currentScript.getAttribute('data-myfunc');

// 校验函数是否存在并调用
if (typeof window[targetFuncName] === 'function') {
    window[targetFuncName]();
} else {
    console.error(`指定的函数 ${targetFuncName} 未在全局作用域定义`);
}

扩展:给函数传递参数

如果需要给目标函数传参,可以新增一个data属性存储参数(用JSON格式字符串),比如:

<script>
function myfunction(num, msg) {
    console.log(`参数:${num},消息:${msg}`);
}
</script>
<script src="http://path/to/widget.js" data-myfunc="myfunction" data-myfunc-args="[1, 'hello']"></script>

对应的widget.js处理代码:

const currentScript = document.currentScript;
const targetFuncName = currentScript.getAttribute('data-myfunc');
const argsStr = currentScript.getAttribute('data-myfunc-args');
// 解析参数数组
const funcArgs = argsStr ? JSON.parse(argsStr) : [];

if (typeof window[targetFuncName] === 'function') {
    window[targetFuncName](...funcArgs);
}

内容的提问来源于stack exchange,提问作者Nawaf Momin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:55:59