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

Retrieve value stored in array with jquery index

本文关键字:数组 存储 jquery 索引 检索 使用      更新时间:2023-09-26

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

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

js

var images = new Array();
$(document).ready( function(){
$('.gallerypreview').each(function() {
    images.push($(this).attr("id"));
});
$('.gallerypreview').click(function() {
var current = $('.gallerypreview').index(this);
});
});

我该如何从这个点击div检索div id ?我可以很好地得到索引号,但是我不能使用任何使用索引#的函数找到索引的值。

var images = new Array();
$(function() {
   $('.gallerypreview').each(function() {
      images.push($(this).attr("id"));
   });
   var current = null;
   $('.gallerypreview').click(function() {
      current = $(this).attr('id');
   });
});

这是你要找的吗?

$('.gallerypreview').click(function() {
var current = $(this).attr("id");
});

在click回调函数中,$(this)引用了被单击的特定DOM对象。因此,简单的.attr("id")将为您获得单击的div的id(存储在变量current中)。

希望有帮助

http://jsfiddle.net/7fPL5/

解决了点击问题,并将id更改为有效的HTML/CSS id (stackoverflow.com/a/79022/1418261)。

JS

var images = new Array();
$(document).ready( function(){
$('.gallerypreview').each(function() {
    images.push($(this).attr("id"));
});
$('.gallerypreview').click(function() {
var current = $('.gallerypreview').index(this);
    alert(current.attr("id"));
});
});
HTML

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

根据变量current的作用域,适当地声明它:

var images = new Array(), current;

然后修改如下:

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

:

$('.gallerypreview').on('click', function() {
    current = this.id;
});

JS FIDDLE DEMO