gpt4 book ai didi

javascript - 将字符串评估为可调用的 JS 函数

转载 作者:行者123 更新时间:2023-11-29 16:15:07 25 4
gpt4 key购买 nike

我需要评估一个保存为字符串的函数,然后在 JS 代码中使用它,场景如下:

第一步

<textarea id="function_text">function test(e){ alert(e.id); }</textarea>

第 2 步

var thatFunction = eval($("#function_text").val()); // returns undefined

步骤 3

thatFunction.call({id: 100});

有办法吗?

附言我知道所有安全注意事项,我只需要在第 3 步收到 100 个警报!

最佳答案

我要给你一个警告,不要这样做,但方法如下:

var thatFunction = Function('return ' + $("#function_text").val())();
thatFunction.call({id: 100});

关于javascript - 将字符串评估为可调用的 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17792271/

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