简体   繁体   中英

How can I call a function when page loads with jQuery?

I want to trigger a JavaScript function after the page loads all the elements and I have to echo some HTTP request data into the page somewhere and use JavaScript to get the information from the DOM.

Therefore, I create the function and fire it on page load using jQuery but it didn't call the javascript (I think the DOM hasn't loaded) so how can I fix this?

  <script>
    $( document ).ready(function(){
        myFunction(); // firing the function 
    });
    </script>
    <script>
    function myFunction(){
    var target = document.getElementById("target");
    var formscount = target.textContent(); // the number of items from [#target]
    alert(target);
    if (formscount > 0) {
        active="";
        for (i=0; i < formscount; i++) {
            var str='active'
            if (i > 0){
            str =  ''
            }
            $('#DOM').append($('SOME HTML ELEMENTS');        
            event.preventDefault()
        }
    }
}

</script>

DOM Called (target) for passing the data ( $_POST['itemscount'] ):

<?
$count = $_POST['itemscount'];
?>

<div id="target" style="display:none;">
<?  $output = $_POST['productscount']; // or $Count //
    echo htmlspecialchars($output); 
?>
</div>

First, textContent is not a function. So it should be written like this:

var formscount = target.textContent;

Second thing, you are missing the closing bracket ) in line $('#DOM').append($('SOME HTML ELEMENTS');

$('#DOM').append($('SOME HTML ELEMENTS'));  

Third thing, event.preventDefault() will not work, as event is undefined. You may remove it.

and lastly, php tags begins with <?php and not with only <? .

<?php
$count = $_POST['itemscount'];
?>

<div id="target" style="display:none;">
<?php
    $output = $_POST['productscount']; // or $Count //
    echo htmlspecialchars($output); 
?>
</div>

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