简体   繁体   中英

Javascript on loaded page not executed

// Change the value of the outputText field
function setAjaxOutput(){
    if(httpObject.readyState == 4){
        document.getElementById('maincontent').innerHTML = httpObject.responseText;
    }
}

i try to load a page which contain this script

<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
$("#formAddUser").validate({
    rules: {
        userImage: {
            required: true,
            accept: "png|jpg|gif|jpeg"
        }
    }
});
});
</script>

<div class="content-box">
<div class="content-box-header">
........................

Why javascript on loaded page not executed? Thank you.

Your problem is that innerHTML doesn't execute scripts in the HTML fragment. When you say 'element.innerHTML = htmlfragment;', it just adds the tags and renders the HTML. Script tags are not rendered as part of the HTML by the browser, so they are ignored.

You need to use jQuery.load() instead of jQuery.ajax() like this:

$('#maincontent').load('yourscript.php');

jQuery.load(); has code inside that first takes those tags out, then adds the remaining HTML via innerHTML, then runs the tags separately. You can see the code that does this here at around line 211. From the docs :

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

first try:

  <script type="text/javascript">

    alert('dfd');

    </script>

and then try

<script type="text/javascript">
    $(document).ready(function() {
    alert('dfd');

    });

</script>

and paste the results.

I believe your form comes with ajax. so it is better if you can turn your validation into a function, and call it inside ajax loaded content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM