如何有效地交换数组元素和变量?

时间:2017-04-28 21:15:25

标签: javascript jquery html

我正在使用jQuery函数来交换我所制作的网格内的图像。唯一的问题是变量返回字符串" url()"这会导致错误。我希望能够正确交换图像,以避免在网格中出现相同的图像两次。

代码:



window.setInterval(function() {
  var imgArray = ["../css/images/work-template/bench/stats2/j.png", "../css/images/work-template/bench/stats2/k.png", "../css/images/work-template/bench/stats2/l.png"]
  var imgSelect = 0 + Math.floor(Math.random() * 2);
  var number = 1 + Math.floor(Math.random() * 8);
  if (number == 1) {
    var imgChange = "one";
  } else if (number == 2) {
    var imgChange = "two";
  } else if (number == 3) {
    var imgChange = "three";
  } else if (number == 4) {
    var imgChange = "four";
  } else if (number == 5) {
    var imgChange = "five";
  } else if (number == 6) {
    var imgChange = "six";
  } else if (number == 7) {
    var imgChange = "seven";
  } else if (number == 8) {
    var imgChange = "eight";
  } else {
    var imgChange = "nine";
  }
  var temp = $("." + imgChange).css("background-image");
  $("." + imgChange).css("background-image", "url(" + imgArray[imgSelect] + ")");
  imgArray.splice(imgSelect, 1, temp);
  alert(imgArray);
}, 500);

<div class="stats__grid--desktop">
  <div class="grid__top">
    <div class="grid__top--item one" style="background-image: url(../css/images/work-template/bench/stats2/a.png);"></div>
    <div class="grid__top--item two" style="background-image: url(../css/images/work-template/bench/stats2/b.png);"></div>
    <div class="grid__top--item three" style="background-image: url(../css/images/work-template/bench/stats2/c.png);"></div>
  </div>
  <div class="grid__mid">
    <div class="grid__top--item four" style="background-image: url(../css/images/work-template/bench/stats2/d.png);"></div>
    <div class="grid__top--item five" style="background-image: url(../css/images/work-template/bench/stats2/e.png);"></div>
    <div class="grid__top--item six" style="background-image: url(../css/images/work-template/bench/stats2/f.png);"></div>
  </div>
  <div class="grid__bottom">
    <div class="grid__top--item seven" style="background-image: url(../css/images/work-template/bench/stats2/g.png);"></div>
    <div class="grid__top--item eight" style="background-image: url(../css/images/work-template/bench/stats2/h.png);"></div>
    <div class="grid__top--item nine" style="background-image: url(../css/images/work-template/bench/stats2/i.png);"></div>
  </div>
</div>
&#13;
&#13;
&#13;

我遇到的问题是当我需要" url("http://www.gohrvst.com/css/images/work-template/bench/stats2/a.png")""/css"时,temp会返回"png"。如何删除这些复杂的字符?

1 个答案:

答案 0 :(得分:1)

您可以从地图/对象中获取字符串值

var data = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six',7: 'seven', 8: 'eight',9: 'nine'}
var number = 1 + Math.floor(Math.random() * 8);
var imgChange = data[number];