getScript or eval in specific location?

眉间皱痕 提交于 2019-12-01 08:03:10

问题


I was wondering if eval (or some variant of jQuery's getScript) can be used to position external javascript in places other than the end of the DOM or at the head. I've tried:

var head = document.getElementById("fig"); 

instead of

var head = document.getElementsById("head")[0];

with

var script = document.createElement("script");
script.text = $(".code").val();
head.appendChild(script);

But I can't seem to get it to work regardless. (The code does work, but Firebug shows the code being replaced both at #fig and at the end of the page, right before the </body> tag.

Basically the JavaScript toolkit I'm using renders things based on where the script tag is located, and I'm trying to dynamically modify the javascript based on user input (hence I can't really refer to a new external JS file - I'd rather run an eval, which isn't ideal).

I guess the worst case scenario would be to save the user input into a "new" file using PHP or something and use getScript pointing to that new PHP file, but it seems exceedingly hacky.

Thank you once again!


回答1:


Does the "JavaScript toolkit" you refer to use document.write or document.writeln to insert output into the page? If so, you could override that function to append the script output into the correct location:

document.write = function(s) {
    $('#fig').append(s);
};

document.writeln = function(s) {
    $('#fig').append(s + '\n');
};

and then load and execute the script using $.getScript.

Edit: A more robust way of doing it, depending on how the code is added:

var output = '';

document.write = function(s) {
    output += s;
};

document.writeln = function(s) {
    output += s + '\n';
};

$.getScript('URL of script here', function() {
    $('#fig').append(output);
});


来源:https://stackoverflow.com/questions/4231948/getscript-or-eval-in-specific-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!