jquery - 使用 "click"函数循环数组

标签 jquery function loops click

我试图拥有它,以便每当单击按钮时它就会更改为下一个背景图像。

var images = [
  "http://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-2-Large.jpg",
  "http://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-6-Large.jpg",
  "http://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-1-Large.jpg"
]

for (var i = 0; i < images.length; i++) {
  $("#changeBg").click(function() {
    $("body").css("background-image", "images.length[i]");
  } 

最佳答案

您的代码中存在一些问题。首先,您需要附加一个单个事件处理程序,并在每个连续的单击事件上处理数组的元素。在循环中附加事件处理程序只会产生冲突,因为您会立即尝试多次执行相同的操作。

在单个事件处理程序中,您可以使用变量来跟踪数组中的当前位置,并在每次单击时递增它。 data 属性非常适合此目的。

其次,您需要实际使用数组元素中的值,而不是将引用括在引号中。您还需要通过索引访问数组,而不是专门通过 length 属性。

最后,您需要将图像的 URL 包装在 url("...") 的 CSS 属性中。

var images = [
  "https://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-2-Large.jpg",
  "https://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-6-Large.jpg",
  "https://helenspeyer.co.uk/wp-content/gallery/the-end-of-the-f-ing-world/The-end-of-the-f...ing-world-1-Large.jpg"
]

$("#changeBg").click(function() {
  var counter = $(this).data('counter') || 0;
  $("body").css("background-image", 'url("' + images[counter % images.length] + '")');
  $(this).data('counter', ++counter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="changeBg">Change background</button>

关于jquery - 使用 "click"函数循环数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49047248/

相关文章:

jquery SlideToggle 图像交换

javascript - 无法访问对象数组

jquery ajax发布错误数据

javascript - 如何在我的游戏中加载上一关而不是下一关?

Swift:如何通过引用函数传递对象数组

python - 在具有特定数字的python循环中生成数字

swift - 在 Swift 中添加表格单元格中的标签总和

Javascript isPunct 函数

python - 迭代计数器 Python3x

javascript - 无限循环不起作用