I tried to update my posts every 5 seconds, like the time is updated, how many users commented and how many likes. this is the code i tried so far Some text1
<div id='poster' class='1'>
<input type='hidden' value='1' id='post_id'>
Some text1
</div>
<div id='poster' class='2'>
<input type='hidden' value='2' id='post_id'>
Some text2
</div>
<div id='poster' class='3'>
<input type='hidden' value='3' id='post_id'>
Some text3
</div>
<div id='poster' class='4'>
<input type='hidden' value='4' id='post_id'>
Some text4
</div>
in the body there is onload='refresh()' here is what's in my java.js:
function refresh(){
var post_id = $("#post_id").val();
setTimeout(refresh_post(post_id),5000);
}
function refresh_post(post_id){
$("."+post_id+"").load("post.php?post_id="+post_id);
}
but it only updates the first div the rest remains the same
答案 0 :(得分:2)
You need to pass the function or its reference which need to be execute to window.setTimeout
Also you need WindowTimers.setInterval()
function refresh(){
var post_id = $("#post_id").val();
setInterval(function(){
refresh_post(post_id)
},5000);
}
Identifiers in HTML must be unique. You can assign conman class and the use class selector
instead. You can store the post_id
in custom data-*
i.e. data-id attributes which can be retrieved using Element.dataset
property or jQuery's .data(key)
HTML
<div class='poster' data-id="1">
<input type='hidden' value='1'>
Some text1
</div>
<div class='poster' data-id="2">
<input type='hidden' value='2' >
Some text2
</div>
<div class='poster' data-id="3">
<input type='hidden' value='3'>
Some text3
</div>
<div class='poster' data-id="">
<input type='hidden' value='4'>
Some text4
</div>
Script
function refresh(){
$('.poster').each(function(){
var post_id = this.dataset.id; // $("#post_id", this).val();
var self = _this;
setInterval(function(){
$(self ).load("post.php?post_id="+post_id);
},5000);
});
}
答案 1 :(得分:0)
Use setinterval if you want to update post at every 5 second continuosly.
setInterval(function(){
$('input:hidden').each(function() {
var post_id = $(this).attr('id');
refresh_post(post_id)
});
}, 5000);
答案 2 :(得分:0)
Method getElementsByClassName() returns a set of DOM elements that have a certain class name.
setInterval(function(){
var elements = document.getElementsByClassName("poster");
for (var i = 0, len = elements.length; i < len; i++) {
var post_id = elements[i].id;
refresh_post(post_id)
}
}, 5000);
答案 3 :(得分:0)
try this
old_html is div id which is you want dynamic load.
newContent geting dynamic div from another page.
<script>
setInterval( function() {
$('div#old_html').load('http://<?php echo $_SERVER['HTTP_HOST'] ?>/pbartest.php #newContent');
}, 5000); </script>