sallushan
sallushan

Reputation: 1147

HTML in string with JavaScript code, JS not working

Here is my test javascript function

<script type="text/javascript">
    function test() {
        var sHTML = "<script type='text/javascript'> " +
                        "function showmsg() { " +
                            "alert('message'); " +
                        "} " +
                     "<\/script>" +
                     "<div>" +
                        "<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
                     "</div>";
        var divTemp = document.createElement("div");
        divTemp.innerHTML = sHTML;

        var d = document.getElementById("div1");
        d.appendChild(divTemp);
    }
</script>

When I run this function, the div along with a tag is added in the div1, but when I click on anchor tag, it says showmsg is not defined, which is indicating that browser is NOT parsing the script tag.

How to achieve this without any 3rd party library?

Update:

The possible usage is, I want to allow user to create HTML templates along with JavaScript code, then my JS library will use those HTML templates to render user defined markup, plus allowing user to implement his/her custom logics through JS.

Upvotes: 0

Views: 943

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

You need to run eval on the script contents when using innerHTML. Try something like:

var scripts = divTemp.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++) {
    eval(scripts[i].textContent);
}

Obviously, you need to do this in end, after injecting the innerHTML into the DOM.

Upvotes: 1

zeomega
zeomega

Reputation: 355

Using jquery, is this can help you :

$('<script>function test(){alert("message");};</' + 'script><div><a href="#" onclick="test();">click</a></div>').appendTo(document.body)

http://jsfiddle.net/TSWsF/

Upvotes: 0

Pointy
Pointy

Reputation: 413717

Browsers do not run JavaScript code when a <script> tag is dynamically inserted like that.

Instead of that, you can just define the function directly!

    function test() {
      window.showmsg = function() {
        alert("message");
      };

      var sHTML = "<div>" +
                    "<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
                 "</div>";
    var divTemp = document.createElement("div");
    divTemp.innerHTML = sHTML;

    var d = document.getElementById("div1");
    d.appendChild(divTemp);
}

Libraries like jQuery have code to strip <script> blocks out of text that's being stuffed into some element's innerHTML, and then evaluate it with eval(), so that's one thing to do if the code is somehow "stuck" in a block of content.

Upvotes: 1

Related Questions