javascript – 在eq()函数jquery中添加多个索引

我想将以下代码添加到我的内容中:

jQuery( ".pt-cv-content:eq(11)" ).attr( "id" , "content11" );

但我很奇怪

Could I add multiple index in eq()?

例如 :

eq(9,10,11).....

谢谢

最佳答案 不,你不能,你需要多个选择器,如下所示:

jQuery( ".pt-cv-content:eq(11), .pt-cv-content:eq(12)" ).attr( "id" , "content11" );

或者您可以将索引存储到数组中并循环遍历它:

var arr = [11,12]; // index 11 and 12
$.each(arr, function(i,e){   
  // this will defined same id name
  // which are not valid
  // as ID must be unique
  // unless you defined it by dynamic values there
  $('.pt-cv-content').eq(e).attr( "id" , "content11" );
});

注意:您应该使用动态内容,因为ID必须是唯一的.

DEMO

点赞