Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Mar 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation Onclick inside innerHTML

    hello,
    what is wrong whis this code?

    <div id="Mydiv">anything</div>
    <script>
    function test(x){alert(x)};
    var col=document.getElementById('Mydiv');
    col.innerHTML='<div onclick="alert(2);test(123);">Text</div>';
    </script>


    notes:
    1-alert(2); works , but test(123) not working , test(44) is working(outside innerHTML)
    2- i want to use parameters inside test() functions i.e: test(123)

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    This is working fine in all tested browsers (Firefox, Chrome): http://jsbin.com/awizux/1/edit

    So the problem must be somewhere else.

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,456
    Thanks
    0
    Thanked 632 Times in 622 Posts
    You can't rely on JavaScript added inside of innerHTML always running correctly across all browsers - Internet Explorer in particular has many restrictions on how and where innerHTML can be used. If you want the HTML to be able to be properly accessed from JavaScript you should add it using DOM mcalls instead of innerHTML.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Specifically, something like:
    Code:
    <div id="Mydiv">anything</div>
    <script>
    function test(x){alert(x)};
    
    var newdiv = document.createElement("div");
    newdiv.innerHTML = "Text";
    newdiv.onclick = function() { test(123); }
    
    mydiv = document.getElementById('Mydiv');
    mydiv.innerHTML = ""; // optional!
    mydiv.appendChild( newdiv );
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •