gpt4 book ai didi

javascript - 在函数声明而不是运行时解析所有变量

转载 作者:行者123 更新时间:2023-11-30 18:22:28 25 4
gpt4 key购买 nike

我想附加一个来自字符串的事件。我遇到的问题是函数名称没有作为字符串传递,而是在调用函数时被编译,这导致 undefined variable 错误 (temp)。

function someFun(arg) {
alert(arg) ;
}

temp[0] = "someFunc(test)" ;//this would be a sample of the incoming HTML
var x = 0 ;
while(temp[x] != '') {
temp[x] = temp[x].replace(')','').split('(') ;//remove paranthesis and separate func name from args
temp[x][1] = temp[x][1].split(',') ;//turn string of args into array
func = function() { window[temp[x][0]].apply(el,[]) ; }
el.addEventListener('click',func,false) ;
x++ ;
}

如果我不使用 temp[x][0](将是 'someFunc')而是直接为 .apply 方法(在本例中为 .apply('someFunc'...) )传入一个字符串,我没有问题,并且将按预期使用 onClick 调用该函数。否则,当我点击元素 el 时,我会得到一个错误,指出没有定义温度。

最佳答案

我很确定,如果您在分配函数之前将 temp[x][0] 分配给一个变量,它应该可以工作。像这样

if (attributes._onClick) {

temp = attributes._onClick;
var x = 0;

while(temp[x] != '') {

var funcSig = temp[x].replace(')','').split('('); //remove paranthesis and separate func name from args

var funcName = funcSig[0];
var funcArgs = funcSig[1].split(','); //turn string of args into array

func = function() { window[funcName].apply(el,[]); }

el.addEventListener('click',function(){
window[funcName].apply(el,funcArgs); }
,false);

x++;
}
}

关于javascript - 在函数声明而不是运行时解析所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11733800/

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