jQuery这个父prev选择器无法正常工作

时间:2015-11-29 09:02:45

标签: javascript jquery css html5 css3

我需要隐藏当前图像并显示父元素表兄弟的视频框

我有这个:



<script>
$(document).ready(function(){
	$("#preview-box-playvideo-btn").click(function(){
		$(this).closest("#preview-box-img").css("display","none");
		$(this).closest("#preview-box-img").prev().fadeIn(600);
	});
});
</script>
&#13;
<div class="prev-img">
			<div id="preview-box-video">
				<embed id="" width="348" height="196" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" allowscriptaccess="always" quality="high" bgcolor="#000000" name="my-video" src="http://www.youtube.com/v/kRyPMsYGb74?enablejsapi=1&version=3&playerapiid=ytplayer&ps=play&vq=large&rel=0&autohide=1&showinfo=0&autoplay=1&authuser=0" type="application/x-shockwave-flash">
				<div id="preview-box-closevideo-btn">X</div>
			</div>
			<div id="preview-box-img">
				<img src="http://www.img3.9minecraft.net/France/Texture-Pack/Atherys-ascended-texture-pack-3.jpg" height="196" width="348">
				<div id="preview-box-playvideo-btn">
					<span>Reproducir video</span>
				</div>
			</div>
		</div>
&#13;
&#13;
&#13;

请,我需要帮助,我不明白为什么它不起作用。

3 个答案:

答案 0 :(得分:1)

你在html中使用id,但是你使用的选择器就像你在使用类一样。我更喜欢使用类,但在你的情况下,给你的id更简单。

<script>
    $(document).ready(function(){
$("#preview-box-playvideo-btn").click(function(){
    $("#preview-box-img").hide();
    $("#preview-box-video").fadeIn(600);
});

});

当你可以使用id直接选择元素时(如将click事件分配给按钮时那样),使用id然后遍历dom树是无稽之谈。

如果你通过使用类来实现它,那么找到最接近两个元素的包含div更安全,然后使用find找到它们中的子元素。

答案 1 :(得分:0)

在此处显示的代码中,prev()选择器实际上可以正常工作。根据您的描述,我假设您说它不起作用,因为视频没有显示出来。是吗?

不知道您决定使用<embed>标记嵌入YouTube视频的原因。首选的方法是使用iframe。如果你转到youtube上的视频并点击&#34;分享&#34; - &GT; &#34;嵌入&#34;,您将获得以下可在您的网站上使用的代码:<iframe width="348" height="196" src="https://www.youtube.com/embed/kRyPMsYGb74" frameborder="0" allowfullscreen></iframe>

这是一个使用iframe代替embed的演示。也是一个首先隐藏视频的CSS。正如您所看到的,您的JS是相同的,它可以很好地隐藏图像并显示视频。

&#13;
&#13;
$(document).ready(function() {
  $(".preview-box-playvideo-btn").click(function() {
    $(this).closest(".preview-box-img").css("display", "none");
    $(this).closest(".preview-box-img").prev().fadeIn(600);
  });
});
&#13;
.preview-box-video {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prev-img">
  <div class="preview-box-video">
    <iframe width="348" height="196" src="https://www.youtube.com/embed/kRyPMsYGb74" frameborder="0" allowfullscreen></iframe>
    <div class="preview-box-closevideo-btn">X</div>
  </div>
  <div class="preview-box-img">
    <img src="http://www.img3.9minecraft.net/France/Texture-Pack/Atherys-ascended-texture-pack-3.jpg" height="196" width="348">
    <div class="preview-box-playvideo-btn"><span>Reproducir video</span>

    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

如果您的文档中没有相同的div,则可以使用:

$("#preview-box-img").css("display","none");
$("#preview-box-img").prev().fadeIn(600);

如果此代码不起作用,您应该确保您的点击处理程序正常。