开发者

getScript or eval in specific location?

开发者 https://www.devze.com 2023-01-26 05:35 出处:网络
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:

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 tool开发者_如何学Ckit 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!


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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消