2016-04-15 106 views
0

我想更改圖像元素的src,爲此我使用此代碼,但當單擊「添加」按鈕時它不起作用,請幫助.... 。如何通過javascript更改src圖像元素

<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Edit Home Page</title> 
     <script type='text/javascript'> 
      function setimgsrc() 
      { 
       $('#image').attr("src",document.getElementById("src").val()); 
      }; 
      </script> 
    </head>  
<body>  
    <div class='center-block'>       
<label >course title: </label>    
<input type="text" id="title" name="title" placeholder="enter title for this course" >    
<br> <label >course description: </label>    
<input type="text" id="des" name="des" placeholder="enter decription for this course" >    
<br> <label >image source : </label>    
<input type='text' id='src' name='src' >    
<input type='button' class='btn' onclick='setimgsrc()' value='add'>    <br> <img id='image' style='width:500px; height:500px' >      </div>  
</body> 
</html> 
+1

什麼「*不起作用*」關於它? – Marcus

回答

0

您不包括jQuery庫。 你的頭的部分應該

<腳本SRC = 「https://code.jquery.com/jquery-1.11.3.js」 > < /腳本>

<script type='text/javascript'> 
     function setimgsrc() 
     { 
      var getImage = $('#src').val();    
      $('#image').attr("src", getImage); 
     }; 
     </script> 

如果你不想使用jquery,那麼你應該重寫setimgsrc()函數如下

功能setimgsrc(){

  var getImage = document.getElementById("src").value;    
      document.getElementById("image").src = getImage;     
     }; 
+0

非常感謝你.....它現在工作 – Ammar

0

你還沒有添加jquery library這裏是更新後的代碼:

<html> 
 
<head> 
 
\t <meta charset="UTF-8"> 
 
\t <title>Edit Home Page</title> 
 
\t <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
 
\t <script type='text/javascript'> 
 
\t \t function setimgsrc() 
 
\t \t { 
 
\t \t \t $('#image').attr("src",$("#src").val()); 
 
\t \t }; 
 
\t </script> 
 
</head>  
 
<body>  
 
\t <div class='center-block'>       
 
\t \t <label >course title: </label>    
 
\t \t <input type="text" id="title" name="title" placeholder="enter title for this course" >    
 
\t \t <br> <label >course description: </label>    
 
\t \t <input type="text" id="des" name="des" placeholder="enter decription for this course" >    
 
\t \t <br> <label >image source : </label>    
 
\t \t <input type='text' id='src' name='src' >    
 
\t \t <input type='button' class='btn' onclick='setimgsrc()' value='add'>    
 
\t \t <br> 
 
\t \t <img id='image' style='width:500px; height:500px' >      
 
\t </div>  
 
</body> 
 
</html>

+0

非常感謝你.....它現在正在工作 – Ammar