开发者

Reload multi webcam(jpg) IMG with jquery

Just stated to play around with Jquery and Java. I stated to setup a page with sevral webcams and updating the live preview image using Jquery. Tryed to google around but I'm not able to find an "easy"开发者_如何学C solution for reloading sevral camera jpegs without reloading the complete page. So far I came up with this and it's "working"

Script part

 $(document).ready(function() {
        setInterval('updateCamera()',2000);
});

function updateCamera() {
        $('#camera1').attr('src','camera1.jpg?' + Math.random());
        $('#camera2').attr('src','camera2.jpg?' + Math.random());
        }

HTML

<img id="camera1" src="camera1.jpg" border=1/>
<img id="camera2" src="camera2.jpg" border=1/>

Anyone who got an better idea / solution for doing this? Like just updating the id element? Sorry if the question is abit "newbie" but there got to be an easier solution for this.


That's a good, simple solution and if it works, just stick with it. You can make it a bit more dynamic if you wish:

function updateCamera() {
    $('.cameras').each(function() {
        var url = $(this).attr('src').split('?')[0];
        $(this).attr('src', url + '?' + Math.random());
    })
}

This way you don't need to specify each of your images separately if you just give them the same classname.


Here is another variation based on Tatu's answer that I just finished using on my own site. It allows me to pass other required arguments to the webcam. It also uses timestamps instead of a random number. That just feels slightly cleaner.

Modify your original image URLs to end with "&t=", and make sure your image tags belong to the class 'cameras'.

<img class="cameras" src="http://kitchen/snapshot.cgi?user=guest&pwd=&t=">


<script type="text/javascript">    

  function updateCamera() {
    time = new Date().getTime();
    $('.cameras').each(function() {
      var url = $(this).attr('src').replace(/&t=\d*/, '&s='+time);
      $(this).attr('src', url);
    })
  }

  $(document).ready(function() {
    setInterval('updateCamera()', 2000);
  });

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜