2012-03-30 45 views
0

所以我试图自动更新使用JavaScript的图像源,但由于某种原因它不会工作。正在从我的php文本生成器(生成带有文本的图像)中检索图像,从输入框中抓取文本。我希望它自动抓取输入框里面的文本,然后更改图像gen.php文本的src = Input_box_text_goes_here使用jQuery更新图像源

这里是我的代码:?

<html> 
    <head> 
     <title>text generator</title> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> 
    </head> 
    <body> 
     <script language=javascript type='text/javascript'> 
      setInterval(function() { 
       var str= document.form.letters.value; 
       $('#logo').src("gen.php?text="+str); 
      }, 10); 
     </script> 
     <img id="logo" name="logo" src="gen.php?text=default" /> 
     <form name="form" action=""> 
      Text: <input type="text" name="letters"/> 
     </form> 
    </body> 
</html> 

任何帮助将不胜感激。

+1

10毫秒的图像请求时间间隔?这会杀死你的浏览器和你的服务器 – Joseph 2012-03-30 23:37:18

回答

2

变化$('#logo').src("gen.php?text="+str);变为$('#logo').attr("src", "gen.php?text="+str);

1

尝试:

<script> 
    $(function(){ 

     //reference the image 
     var img = $('#logo'); 

     //use onkeyup instead of polling 
     $('input[name="letters"]').on('keyUp',function(){ 

      //get the value every keystroke 
      var inputValue = $(this).val(); 

      //apply the values to the image source 
      img.each(function(){ 
       this.src = "gen.php?text="+inputValue; 
      }); 
     }); 
    }); 
</script>