如何检测指定wrapper父容器内是否存在iframe元素及data-src属性
解决方案
之前写法失效的原因
videoWrapper.parents().eq(2).find('iframe')是向上查找videoWrapper的祖先元素,完全找反了方向,所以匹配不到子元素里的iframe- 如果
videoWrapper是原生DOM对象,直接调用jQuery方法(find()/contents()等)会报错,自然没有返回结果 .contents()是用来获取子元素包括文本节点、注释节点,普通查找iframe不需要用这个方法
方案1:基于jQuery实现
如果你的项目已经引入了jQuery,调整写法如下:
// 先将原生DOM对象转为jQuery对象,如果本身就是jQuery对象可跳过这一步 const $videoWrapper = $(videoWrapper); // 查找所有子层级中带data-src属性的iframe const targetIframes = $videoWrapper.find('iframe[data-src]'); // 判断是否存在匹配的iframe const hasTargetIframe = targetIframes.length > 0; if (hasTargetIframe) { // 取第一个匹配的iframe const iframe = targetIframes.eq(0); // 获取data-src属性值 const dataSrc = iframe.attr('data-src'); // 后续业务逻辑 }
如果确认iframe只在1-2层嵌套,可以缩小查找范围提升效率:
const targetIframes = $videoWrapper.children('iframe[data-src]').add($videoWrapper.children().find('iframe[data-src]'));
方案2:原生JavaScript实现
不需要依赖jQuery的纯原生写法:
// 查找所有子层级中带data-src属性的iframe const targetIframes = videoWrapper.querySelectorAll('iframe[data-src]'); const hasTargetIframe = targetIframes.length > 0; if (hasTargetIframe) { const iframe = targetIframes[0]; const dataSrc = iframe.dataset.src; // 后续业务逻辑 }
额外排查建议
如果调整写法后还是匹配不到,优先检查两个点:
- 执行时机:如果iframe是接口请求完成后动态渲染的,要等DOM渲染完成后再执行检测逻辑,不要放在页面初始化的同步代码里
- 父容器指向是否正确:打印
console.log(videoWrapper)确认节点是你预期的父容器,不要选错了根节点
内容的提问来源于stack exchange,提问作者user16645285
相关产品推荐
相关产品推荐

