将jQuery函数作为字符串传递

时间:2019-09-06 11:01:03

标签: javascript jquery

故事的背景:

  • 我有几个网页需要填写许多输入字段的数据;

  • 为了不浪费时间(测试时),我有一个JavaScript文件可以帮助我(我正在e2e测试中使用它);

  • 我在浏览器中创建了一个书签,并将其添加为URL:

enter image description here

URL VALUE: javascript:(function()document.body.appendChild(document.createElement('script')).src='../path_to_another_js_file.js')();
  • 此路径src='../path_to_another_js_file.js'将打开一个具有以下内容的 js 文件:
(function ($) {
    var fieldData = {
        "ContactData.EMail": "test@test.com",
        "ContactData.EMailConfirmation": "test@test.com",
        etc...
    };
})(jQuery);

问题

我想从书签中删除src='../path_to_another_js_file.js',而不是从该路径中删除,以将该外部文件中的函数作为字符串传递,如下所示:

javascript:(function()document.body.appendChild(document.createElement('script'))
.textContent(String(
    (function ($) {
        var fieldData = {
            "ContactData.EMail": "test@test.com",
            "ContactData.EMailConfirmation": "test@test.com",
            //etc...
        };
    })(jQuery);
))})();

在任何情况下我都无法执行此操作,因为由于某些语法问题,该操作将不会执行/甚至不会在我的FE中创建js脚本。

你们有没有遇到过我这里遇到的同样情况?? 10倍

2 个答案:

答案 0 :(得分:1)

您的代码应如下所示:

javascript:(function ($) {
    var fieldData = {
        "ContactData.EMail": "test@test.com",
        "ContactData.EMailConfirmation": "test@test.com",
        etc...
    };
})(jQuery);

不需要脚本标签。此外,您在书签功能的主要功能中缺少花括号也有错误。

答案 1 :(得分:0)

您已经接近,但是存在一些语法问题。这应该与您现在拥有的脚本标签相同:

javascript:(function(){
    var el = document.createElement('script');
    el.innerHTML = `(function ($) {
    var fieldData = {
        "ContactData.EMail": "test@test.com",
        "ContactData.EMailConfirmation": "test@test.com",
        //etc...
    };
})(jQuery);`;
    document.body.appendChild(el);
})();
相关问题