e.preventDefault无法在Firefox中运行跳转到目标上的页面顶部

时间:2012-03-29 02:44:53

标签: javascript-events jquery

我有一个页面,我试图制作一个通用样式的标签,这个功能将用于基本上隐藏所有标签内容并显示单击的一个。这一切都很好,除了在Firefox中,它仍然触发默认操作并在您单击目标时跳转页面。奇怪的是,如果你点击已经打开的那个,它就不会跳跃。在示例代码中,只有2个选项卡和内容集,但它可以更容易。

<div id="recentGalleryBox">
  <ul class="tabs">
    <li class="active"><a href="#recentVideo" title="latest videos">Latest Videos</a></li>
    <li class="last"><a href="#recentPhoto" title="latest photos">Latest Photos</a></li>
  </ul>
  <div class="tabsContent bgNone">
    <div id="recentVideo">
      <img src="http://i.ytimg.com/vi/Ymjh5ZV1H48/0.jpg" class="articleImage vidThumb" />      
      <p class="readmore"><a href="/galleries/videos" title="View all photos">View all video galleries</a></p>
    </div>  
    <div id="recentPhoto">
      <img src="/images/sized/dev/images/uploads/gallery/genericphoto-280x175.jpg" width="280" height="175"  alt="Album Image" class="articleImage" />
      <p class="readmore"><a href="/galleries/photos" title="View all photos">View all photo galleries</a></p>
    </div>
  </div>
</div>

$(document).ready(function(){
  $('#recentPhoto').hide();
  $('.tabs li a').click(function(e){
    var reveal = $(this).attr("href");
    var theid = ""
    $(this).parents('ul').children('li').removeClass('active');
    $(this).parent().addClass('active');
    $(this).parents('ul').next().children().each(function(idx, item){
      theid = "#"+$(item).attr("id");
      if (reveal != theid) {$(theid).hide();}
    });
    $(reveal).fadeIn();
    e.preventDefault();
  });
});

1 个答案:

答案 0 :(得分:1)

不相关,但您缺少分号

var reveal = $(this).attr("href");
var theid = ""

- 编辑感谢@Interstellar_Coder指出这一点:) 在theid之后没有分号,解析器足够聪明,可以添加缺少的半冒号,但保持一致是很好的。

问题是当你打电话给if (reveal != theid) {$(theid).hide();}时,因为内容基本上只包括那个,一个实例的整个文档的高度为0,因此你会感觉到由于点击而“跳”到顶部。

如果#recentGalleryBox以下有足够的空间,则问题就消失了

http://jsfiddle.net/B9M2k/14/