开发者

load a javascript function via string

How to load a javascript function via string

<div id="test_div">display here</div> // < --display here


<script type="text/javascript">

// string 
var _script=("<script type=\"text/javascript\">

    var disqus_shortname = 'example'; 
    (function () {
        var s = document.createElement('script'); s.async = true;
        s.type = 'text/javascript';
        s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appe开发者_运维问答ndChild(s);
    }());
</script>");


// write/output the string
document.getElementById('test_div').innerHTML= _script;
</script>


JavaScript does not allow new lines inside strings, you need escape each new line with a \.

var _script=("<script type='text/javascript'>\
    var disqus_shortname = 'example';\
    (function () {\
        var s = document.createElement('script'); s.async = true;\
        s.type = 'text/javascript';\
        s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';\
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);\
    })();\
</script>");


Using jQuery

$('#test_div').click(yourFunctionName)

You need to name your function in the script

<script type="text/javascript">

// string 

var _script=("<script type=\"text/javascript\">

var disqus_shortname = 'example'; 
(function yourFunctionName () {
    var s = document.createElement('script'); s.async = true;
    s.type = 'text/javascript';
    s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
    (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());


</script>");

I assumed you meant that if you click on the testdiv it should do the function?

Or -- Did you mean you want to load the script dynamically into your webpage?! Ahhhh OK!

Using jQuery Again.

$(body).append('<script type="text/javascript">' + YOUR_JAVA_STRING + '</script>');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜