[英]changing img src through jquery click function
我想用jquery click功能更改我的img src,但似乎做不到。這是我的html代碼:
<div id="main2"><img id='mty' style="width: 500px;height: 600px;"
src="https://cdn.pastemagazine.com/www/articles/morty%20main.jpg">
</div>
這是我的jQuery代碼將無法正常工作:
<script type="text/javascript">
$('#paper').click(function()
{
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
}); </script>
我究竟做錯了什么? 如果我單擊#paper wich是一個按鈕,我想更改html src!
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
您需要將“ src”設置為img標簽,而不是div標簽
<script type="text/javascript">
$(document).ready(function(){
$('#paper').click(function() {
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
});
});
</script>
HTML是-
<button type="button" id="paper">change image</button>
<div id="main2">
<img id='mty' style="width: 500px;height: 600px;"
src="https://cdn.pastemagazine.com/www/articles/morty%20main.jpg">
</div>
腳本-
<script type="text/javascript">
$('#paper').click(function () {
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
});
</script>
要記住的事情-
html渲染后的用戶腳本或准備使用jquery。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="style.css" /> <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body> <img id="image" src="http://lorempixel.com/400/200" alt="random image"/> <button id="changeImage">Change image</button> <script> $('#changeImage').on('click', function(){ $('#image').attr('src', 'http://lorempixel.com/400/200'); }); </script> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.