使用相同的类缩短 jQuery 选择器

时间:2021-08-01 20:51:14

标签: javascript jquery

我得到以下 jQuery 代码:

Autentication

如何保存以一遍又一遍地写整个$(document).ready(function () { let li_studio = $('#studio_gallery .wpb_image_grid_ul li:nth-child(2), #studio_gallery .wpb_image_grid_ul li:nth-child(3), #studio_gallery .wpb_image_grid_ul li:nth-child(4)'); let width = li_studio.outerWidth(); li_studio.css('height', width); }); ?这个选择器中唯一改变的是孩子的编号。

1 个答案:

答案 0 :(得分:0)

你可以预先构建你的字符串:

let selectors = [];
for (const i = 2; i++; i<5) {
  selectors.push(`#studio_gallery .wpb_image_grid_ul li:nth-child(${i})`);
}
let li_studio = $(selectors.join());

编辑: 您应该能够在 jquery 元素中保存“#studio_gallery .wpb_image_grid_ul”,例如:

const $el = $('#studio_gallery .wpb_image_grid_ul');

然后使用它:

let li_studio = $([$el.find('li:nth-child(2)'), $el.find('li:nth-child(3)')])

如果这就是你要找的东西