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

jvidinwx  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(96)

我正在使用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);

个字符

nnvyjq4y

nnvyjq4y1#

您可以从map / object获取字符串值

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];

字符串

相关问题