我对 JavaScript 很陌生, 我创建了一个图像 slider ,但现在我想要一个按钮,即:人类和机器人, 如果单击“人”按钮,当前图像显示为“人”,我想要一个 警报消息...该怎么做?我需要将图像存储在数组中吗?完全令人困惑......需要尽快......
<code>
<pre>
<html>
<head>
<script src="jquery-1.12.2.min.js"></script>
<script src="main.js"></script>
<script>
function swapImages(){
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
$active.fadeOut(function(){
$active.removeClass('active');
$next.fadeIn().addClass('active');
});
}
$(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 200);
})
</script>
<style>
#myGallery{
position:relative;
width:400px; /* Set your image width */
height:300px; /* Set your image height */
}
#myGallery img{
display:none;
position:absolute;
top:0;
left:0;
}
#myGallery img.active{
display:block;
}
</style>
</head>
<body>
<div id="myGallery">
<img src="image1.png" class="active" id="1" />
<img src="image2.png" />
<img src="image3.png" />
</div>
<button id="bt1" >Human</button>
<button id="bt2" >robot</button>
</body>
</html>
</pre>
</code>
最佳答案
所做的更改
$("#bt1,#bt2").click(function() {
alert($('img.active').attr('src'));
});
工作演示
function swapImages() {
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
$active.fadeOut(function() {
$active.removeClass('active');
$next.fadeIn().addClass('active');
});
}
$(document).ready(function() {
$("#bt1,#bt2").click(function() {
alert($('img.active').attr('src'));
});
setInterval(swapImages, 200);
});
#myGallery {
position: relative;
width: 400px;
/* Set your image width */
height: 300px;
/* Set your image height */
}
#myGallery img {
display: none;
position: absolute;
top: 0;
left: 0;
}
#myGallery img.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myGallery">
<img src="image1.png" class="active" id="1" />
<img src="image2.png" />
<img src="image3.png" />
</div>
<button id="bt1">Human</button>
<button id="bt2">robot</button>
关于javascript - onclick 按钮获取事件图像信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36299714/