How to call a javascript function defined in a script tag?

喜你入骨 提交于 2019-12-01 13:36:13

问题


Example:

<script type="text/javascript">
    function test() {
        console.log("Hello world");
    }
</script>

How would I call test()?

Edit: I didn't explain this correctly.

I am using the request module of node.js to load an external html file that contains javascript functions:

request.get(options, function (error, response, body) {
    if (error && response.statusCode !== 200) {
    }
    else {
        jsdom.env({
            html: body,
            scripts: ["../jquery-1.6.4.min.js"]
        }, function (err, window) {
            var $ = window.jQuery;

I'm just looking for the syntax to call a function in 'body'.


回答1:


Just call it like any other function on your page, jQuery is a framework and is not needed for running a JS function.




回答2:


So the problem here is that by default, jsdom.env does not execute javascript found while processing markup.

You'll need to turn these features on:

jsdom.env({
  // ...
  features : {
    FetchExternalResources : ['script'],
    ProcessExternalResources : ['script']
  }
});

FetchExternalResources controls whether or not jsdom should even bother reaching across the network/disk to collect the bytes of a resource

ProcessExternalResources controls whether or fetched scripts are executed

Note these names were chosen to encompass other resources types (read: images, css, etc..) which will be added in the future. The idea here is to provide sane defaults, but have many turnable knobs that affect the behavior of jsdom.




回答3:


hmmm... probably I'd go with

test();

But that's not jquery, it's plain old javascript.




回答4:


Try this:

 ...

     function (err, window) {
                    var $ = window.jQuery;
                    window.test();

...

You could also try:

<script type="text/javascript" id="myscript">
    function test() {
        console.log("Hello world");
    }
</script>

And then:

function (err, window) {
                        var $ = window.jQuery;
                        (1,window.eval)( $("#myscript").html() );
                        window.test();


来源:https://stackoverflow.com/questions/8345054/how-to-call-a-javascript-function-defined-in-a-script-tag

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