简体   繁体   中英

Jquery appending to div

i am trying to append to a div with an ID that is dynamic

                <script>
                    var GameId = "{{$match['gameId']}}";
                    var Ts = '{{$match['createDate']}}';
                    var TsInt = parseInt(Ts);
                    var timeSinceGame = moment(TsInt).fromNow();
                    $('#'+GameId).append(timeSinceGame );
                </script>

the script is run inside of a php foreach loop.

the div ID is set the same as GameID variable however nothing is appended to anything when run what's wrong here?

None of your jQuery is wrapped in DOM ready events, so the elements are likely not in the DOM yet when the code runs.

Try adding a DOM ready wrapper:

<script>
    $(function(){
        var GameId = "{{$match['gameId']}}";
        var Ts = '{{$match['createDate']}}';
        var TsInt = parseInt(Ts);
        var timeSinceGame = moment(TsInt).fromNow();
        $('#'+GameId).append(timeSinceGame );
    });
</script>

$(function(){ is just a handy shortcut for $(document).ready(function(){

The alternative is to simply inject your code after the elements in the page, so that they do already exist.

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