我想使用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,我希望能够更改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>