javascript - onclick 按钮获取事件图像信息

标签 javascript jquery button slider

我对 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/

相关文章:

javascript - 单击按钮即可更改其余按钮的颜色

javascript - 如何根据 slider 值动态设置 jquerymobile slider 的步长?

c# - 在 C# 中将标准按钮组合在一起

c# - MouseLeftButtonUp 不触发

Javascript 根据一天中的时间每分钟显示一张图像

javascript - 如何在 html5 native 视频播放器中添加延迟或偏移以同步 webvtt 字幕?

javascript 文件读取器 : preview for images in multiple files batches

jquery - 围绕环设置动画 SVG 电子

jquery - 如何将 JQuery 可排序/拖放与模型同步?

html - 根据内容/标签优化按钮宽度