javascript - Jquery:在 jquery 的(字符串)变量中执行 jquery 脚本

标签 javascript jquery html ajax

我知道这是一个有点令人困惑的问题。请让我详细说明。

我需要执行从 ajax 请求获取的文本文件中编写的 jquery 脚本

例如我从 ajax 请求中获取以下代码

($($("#jstreeblock").children().children().children()[0]).children('li').attr('id'))

我需要执行上述脚本的结果并将其存储在变量中。

另一个简单的例子。 我已经得到了

'a'+'b'

如果我执行上面的脚本,结果将为ab,但如果我使用eval运行它,我会收到错误

脚本

<script>
var a = "'a'+'b'"
console.log(a); // printing 'a'+'b'
eval(a); // it should give ab but not giving any result
</script>

如果我运行它

eval(''a'+'b'') 

出现错误,如下所示

错误

VM157982:1 Uncaught SyntaxError: Unexpected string(…)(anonymous function) @ VM157981:2InjectedScript._evaluateOn @ VM156978:878InjectedScript._evaluateAndWrap @ VM156978:811InjectedScript.evaluate @ VM156978:667

请帮忙,非常感谢

最佳答案

通常 eval 在这种情况下应该可以工作。但真的不知道你怎么调用它。您说您将其称为 eval(''a'+'b''),应该是 eval("'a'+'b'") 。这也可能是原因。

现在,关于eval,按照@Sosdoc的建议使用它是一个危险的想法。但是,为了解决您的情况,请检查此 fiddle我有一个模拟的 json 响应,并且 eval 工作正常。我还添加了[评论]您的 "'a'+'b'" 案例。您也可以检查一下。它应该为您提供 ab 结果。

还可以从用户 @Chocula here 找到这个出色的答案欲了解更多信息,

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

关于javascript - Jquery:在 jquery 的(字符串)变量中执行 jquery 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280988/

相关文章:

javascript - 使用 React-Context 时对象不可迭代错误

javascript - 动态传递参数给applet

javascript - 新的 Instagram API,如何通过标签获取帖子

jquery - 循环遍历来自ajax成功消息谷歌图表的json数据

javascript - 按下按钮时百分比条上升

PHP $_GET 撇号

Javascript为什么实例化不是instanceof声明的类?

javascript - 为什么这个 JavaScript 不动态创建对象属性?

ajax - 如何获取 jQuery.ajax 响应状态?

jquery - 我应该为客户可能使用的所有不同浏览器编写 jquery 吗?