Jquery在点击时随机更改图像

时间:2015-06-29 04:23:34

标签: jquery html

Html

    <body>
        <img class = die src="one.jpg">
        <img class = die src="two.jpg">
        <img class = die src="three.jpg">
        <img class = die src="energy.jpg">
        <img class = die src="hit.jpg">
        <img class = die src="heal.jpg">
    </body>

Jquery的

 var dice = ["one.jpg","two.jpg","three.jpg","energy.jpg","hit.jpg","heal.jpg"];
    $(function() {
        $('.die').click(function() {
            var num = Math.floor(Math.random()*dice.length);
            $(this).html('<img src="'+dice[num]+'">');
        });
    });

每当我测试它时,它都不会改变图像 谢谢你的时间

1 个答案:

答案 0 :(得分:2)

您需要更改已点击的img的src属性

&#13;
&#13;
$(function() {
  //var dice = ["//placehold.it/64X64&text=1", "//placehold.it/64X64&text=2", "//placehold.it/64X64&text=3", "//placehold.it/64X64&text=4", "//placehold.it/64X64&text=5", "//placehold.it/64X64&text=6"];

  //create the array dynamically using the .die elements
  var dice = $('.die').map(function() {
    return $(this).attr('src')
  }).get();

  $('.die').click(function() {
    var num = Math.floor(Math.random() * dice.length);
    //This may not change the image always as the same src can be selected by this logic
    $(this).attr('src', dice[num]);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="die" src="//placehold.it/64X64&text=1">
<img class="die" src="//placehold.it/64X64&text=2">
<img class="die" src="//placehold.it/64X64&text=3">
<img class="die" src="//placehold.it/64X64&text=4">
<img class="die" src="//placehold.it/64X64&text=5">
<img class="die" src="//placehold.it/64X64&text=6">
&#13;
&#13;
&#13;

die元素是img元素,您无法设置innerHTML img元素,而是需要更改src }属性来更改图像

如果您想在每次点击中更改图像

&#13;
&#13;
$(function() {
  //var dice = ["//placehold.it/64X64&text=1", "//placehold.it/64X64&text=2", "//placehold.it/64X64&text=3", "//placehold.it/64X64&text=4", "//placehold.it/64X64&text=5", "//placehold.it/64X64&text=6"];

  //create the array dynamically using the .die elements
  var dice = $('.die').map(function() {
    return $(this).attr('src')
  }).get();

  $('.die').click(function() {
    var src, curr = $(this).attr('src');
    do {
      src = dice[Math.floor(Math.random() * dice.length)]
    } while (src == curr);
    $(this).attr('src', src);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="die" src="//placehold.it/64X64&text=1">
<img class="die" src="//placehold.it/64X64&text=2">
<img class="die" src="//placehold.it/64X64&text=3">
<img class="die" src="//placehold.it/64X64&text=4">
<img class="die" src="//placehold.it/64X64&text=5">
<img class="die" src="//placehold.it/64X64&text=6">
&#13;
&#13;
&#13;