Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery索引检索存储在数组中的值_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 使用jquery索引检索存储在数组中的值

Javascript 使用jquery索引检索存储在数组中的值,javascript,jquery,html,css,Javascript,Jquery,Html,Css,当用户单击div标记时,我想将相应的id值存储在varcurrent中,以便以后可以使用它迭代到该索引,从而可以显示和隐藏div html <div class="gallerypreview" id="1"></div> <div class="gallerypreview" id="2"></div> <div class="gallerypreview" id="3"></div> 如何从单击的div中检索divid

当用户单击
div
标记时,我想将相应的
id
值存储在var
current
中,以便以后可以使用它迭代到该索引,从而可以显示和隐藏div

html

<div class="gallerypreview" id="1"></div>
<div class="gallerypreview" id="2"></div>
<div class="gallerypreview" id="3"></div>

如何从单击的div中检索div
id
?我可以很好地得到索引号,但是我无法使用任何使用索引的函数来找到索引的值。

这就是您要查找的吗

$('.gallerypreview').click(function() {
var current = $(this).attr("id");
});
在click回调函数
$(this)
中引用了被单击的特定DOM对象。因此,一个简单的
.attr(“id”)
将为您获取单击的div的id(存储在变量
current
中)

希望有帮助

var images = new Array();

$(function() {

   $('.gallerypreview').each(function() {
      images.push($(this).attr("id"));
   });

   var current = null;
   $('.gallerypreview').click(function() {
      current = $(this).attr('id');
   });
});
解决单击问题,并将ID更改为有效的HTML/CSS ID(stackoverflow.com/a/79022/1418261)

JS

HTML

1
2.
3.

根据当前变量的范围适当声明:

var images = new Array(), current;
然后更改以下内容:

$('.gallerypreview').click(function() {
var current = $('.gallerypreview').index(this);
});
致:


切勿以数字()开头ID或类。这可能会导致某些浏览器无法正确解释ID。看起来您只是在循环中编写代码,以获取对单击的div的引用。您似乎不需要数组、迭代器,甚至元素ID。您可以通过以下方式获得对单击元素的引用:
var current$('.gallerypreview')。单击(函数(){current=this;})<div class="gallerypreview" id="one">1</div>
<div class="gallerypreview" id="two">2</div>
<div class="gallerypreview" id="three">3</div>
var images = new Array(), current;
$('.gallerypreview').click(function() {
var current = $('.gallerypreview').index(this);
});
$('.gallerypreview').on('click', function() {
    current = this.id;
});