我想用jquery点击功能改变我的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>
我在做错了什么?我希望能够改变html src,如果我点击#paper这是一个按钮顺便说一句
TY!
答案 0 :(得分:2)
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
你需要设置&#34; src&#34; 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>
答案 1 :(得分:0)
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 ready。
答案 2 :(得分:0)
<!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>
&#13;