使用带有 jQuery/JS 的通配符按类选择元素

Select elements by class using wildcard with jQuery/JS

提问人:Line One 提问时间:3/24/2023 最后编辑:Line One 更新时间:3/24/2023 访问量:27

问:

我已经看到了处理在CSS中选择元素的答案,我想知道是否可以在jQuery中使用通配符用一行执行以下操作?

jQuery('.youtube-video-1')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('.youtube-video-2')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('.youtube-video-3')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');

我试过:

jQuery('.youtube-video-\\S*')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('[class^=youtube-video-]')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jquery jquery-selectors 通配符

评论

1赞 Kevin B 3/24/2023
这涵盖了如何构建选择器,但是使用集合而不是一个元素的处理也是不正确的。[0] 将始终将集合减少到 1 个元素,而不是全部元素。
2赞 Heretic Monkey 3/24/2023
为什么不直接向所有元素添加一个类呢?youtube-video
0赞 mplungjan 3/24/2023
@KevinB [0] 在这里用于获取 SINGLE iframe 的 DOM 元素,因此 Heretic Monkey 的建议更好,甚至最好在这里根本不使用 jQuery。class="youtube-video-1"document.querySelectorAll('youtube-video-class').forEach(vidFrame => vidFrame.contentWindow.postMessage(.....))
1赞 Kevin B 3/24/2023
@mplungjan当然,使用单个类名不会影响 [0] 问题。在这两种情况下,这也必须得到解决。
0赞 Line One 3/24/2023
我会尝试你的建议@Heretic猴子

答: 暂无答案