-2

我想打印所有以前的图像 ID 以进行检查。因为当我使用以下代码将类添加到所有以前的类时,图像不会添加到相应的类中。

$(document).on('click', 'img', function() {
   var t=$(this);
   t.prevAll().removeClass('t2').addClass('t1');
   t.nextAll().removeClass('t1').addClass('t2');

检查这个 jsFiddle。单击任何图像时,我想将以前的图像添加到不同的类,将下一个图像添加到不同的类。

4

2 回答 2

1

Those img elements do not have id attribute, assuming they will have id attribute in near future, you can use map method:

var ids = t.prevAll().removeClass('t2').addClass('t1').map(function(){
      return this.id;
}).get().join();

console.log(ids);

the images are not added to corresponding classes.

However, it seems you want to add a class to the clicked element too, if this is the case use addBack method:

t.nextAll().addBack().removeClass('t1').addClass('t2');

http://jsfiddle.net/8an7J/

于 2013-05-29T06:25:11.537 回答
1

well, you could use .map

For example, to get a comma-separated list of checkbox IDs:

var numbers = $(':checkbox').map(function() {
      return this.id;
}).get().join();

alert(numbers);

The result of this call is the string, "two,four,six,eight".

于 2013-05-29T06:25:18.567 回答