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



我得到了以下jQuery代码:

$(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);
});

我怎样才能一遍又一遍地写整个#studio_gallery .wpb_image_grid_ul?在这个选择器中唯一改变的是子元素的个数。

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

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());

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

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

然后使用:

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

如果这是你想要的

相关内容

  • 没有找到相关文章

最新更新