2016-04-15 108 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