[英]changing img src through jquery click function
i wanna change my img src with jquery click function but cant seem to do it.here is my html code: 我想用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>
Here is my jquery code that won't work: 这是我的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>
what am i doing wrong? 我究竟做错了什么? i wanna be able to change the html src if i click on #paper wich is a button btw ty! 如果我单击#paper wich是一个按钮,我想更改html src!
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
You need to set "src" to img tag, not the div tag 您需要将“ 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 is as- 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- 脚本-
<script type="text/javascript">
$('#paper').click(function () {
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
});
</script>
Things to remember- 要记住的事情-
User script after html render or use jquery ready. 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.