我在HTML中有多个嵌入式youtube视频,因此当用户单击CSS类.vma_overlay
时,我想获取最接近的iframe的src。
我尝试了以下操作,但无法正常工作:
$(".vma_overlay").click(function() {
data = $(event.target).closest('.vma_iFramePopup').attr("src");
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class=" ">
<div class="container">
<div class="row">
<div class="sizer" style="width:100%">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item vma_iFramePopup" src="https://www.youtube.com/embed/w5ln_-A3aw0?enablejsapi=1&origin=http%3A%2F%2Flocalhost%3A57299" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true"
id="874685300"></iframe>
<div class="vma_overlay visible-lg" data-toggle="modal" data-target="#vma_ModalBox"></div>
</div>
</div>
</div>
</div>
</section>
任何帮助我朝正确方向前进的帮助都将不胜感激。
答案 0 :(得分:1)
iframe不是.vma_overlay
的父元素,因此closest()
找不到它,而是“同级”,因此您可以使用jQuery siblings()
< / strong>方法,如:
data = $(event.target).siblings('.vma_iFramePopup').attr("src");
$(".vma_overlay").click(function() {
data = $(event.target).siblings('.vma_iFramePopup').attr("src");
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class=" ">
<div class="container">
<div class="row">
<div class="sizer" style="width:100%">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item vma_iFramePopup" src="https://www.youtube.com/embed/w5ln_-A3aw0?enablejsapi=1&origin=http%3A%2F%2Flocalhost%3A57299" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true"
id="874685300"></iframe>
<div class="vma_overlay visible-lg" data-toggle="modal" data-target="#vma_ModalBox">CLICK ME</div>
</div>
</div>
</div>
</div>
</section>
答案 1 :(得分:0)
最近在这里不起作用:
说明:对于集合中的每个元素,通过测试元素本身并遍历DOM树中的祖先,获得与选择器匹配的第一个元素。
尝试siblings()
https://api.jquery.com/siblings/
答案 2 :(得分:0)
您可以尝试
$(".vma_overlay").click(function (event) {
data = $(event.target).parent().find('iframe.vma_iFramePopup').attr("src");
console.log(data);
});