如何增加jQuery变量? [英] How to increment jQuery variable?

查看:72
本文介绍了如何增加jQuery变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jquery浏览图片库,所以我有一个按钮,该按钮应该将变量增加1,然后使用该按钮加载下一张图片.

I'm trying to browse through a picture gallery with jquery, so I have a button which is supposed to increment a variable by 1 and then use that to load the next picture.

这个 SO问题上使用最高答案,我认为这将是解决方案:

Using the top answer on this SO question, I thought this would be the solution:

<div id="pic"></div>
<div id="browse-right">NEXT</div>

<%= image_tag("/1.JPG", id:"1") %>
<%= image_tag("/2.JPG", id:"2") %>
<%= image_tag("/3.JPG", id:"3") %>

$("#1").click(function() {
  var x = 1;
  $("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#2").click(function() {
  var x = 2;
  $("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#3").click(function() {
  var x = 3;
  $("#pic").html('<img src="/' + x + '.JPG" />');
});
//...
$("#browse-right").click(function() {
  x = x + 1;
  $("#pic").html('<img src="/' + x + '.JPG" />');
});

但是它只是重新加载同一张图片,这意味着var x不会改变.有人知道正确的语法吗?

But it just reloads the same picture, which means var x doesn't change. Anyone know the proper syntax?

更新:好的,我想我已经解决了问题. x是在单击图片时设置的,显然在功能完成后它不会持续存在.我没有在原始代码中包含该部分,因为我认为这会使整个内容变得更复杂,阅读起来…….设置功能后,如何使x保留下来?

UPDATE: Okay, I think I've figured out the problem. x is set when a picture is clicked on, and apparently it isn't persisting after the function is complete. I didn't include that part in the original code because I thought it would make the whole thing more complicated to read.....lesson learned. How can I get x to persist after the function it is set in?

推荐答案

设置了x的函数后,如何使x保持不变?

How can I get x to persist after the function it is set in?

尝试在click处理程序之外和之前定义x

Try defining x outside of and before click handler

var x = 1;
$("body").on("click", function() {
  x = x + 1;
  $(this).html(x)
})

body {
  width: 300px;
  height: 300px;
  border: 1px solid purple;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
click

这篇关于如何增加jQuery变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆