"未定义不是函数"错误jQuery,.replace,scrollTop

时间:2015-03-21 21:56:14

标签: javascript jquery html undefined

这个滚动功能不起作用......我认为它不能“找到”我的html中的ID,但我不明白为什么。我有一个早期版本(我没有提交D :),这似乎工作得很好。我以为我已经像以前一样重写了它,但我猜不是。

JS

$(document).ready(function() {


$(function() {
$(".navlist").on("click", function() {
  $(".navlist").removeClass("active");
  $(this).addClass("active");
});

});

function goToByScroll(id){
  // Remove "link" from the ID
  id = $(id).replace("link", "");
  // Scroll
  $('html,body').animate({
scrollTop: $("#"+id).offset().top}, 'slow');

}

$(".navbar > ul > li > a").click(function(e) { 
      // Prevent a page reload when a link is pressed
    e.preventDefault(); 
      // Call the scroll function
    goToByScroll($(this).attr("id"));           
});

});

HTML

<body>

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <ul class="nav navbar-nav" >
    <li class="navbar-brand"><img width="100%" height="100%" src="sa.png"></li>
    <li class="navlist"><a id ="homelink" href="#">HOME</a></li>
    <li class="navlist"><a id = "portfoliolink" href="#">WORK</a></li>
    <li class="navlist"><a id = "contactlink" href="#">CONTACT</a></li>
  </ul>
</nav>

<section class="jumbotron_index"> 
  <p class= "scrollhome" id ="home"> scroll to home </p>
  <div class="content"> 
    <h1>  </h1>
    <h2>  
      <a href="" target="_blank"><img width="2%" height="2%" src="gh.png"></a></h2>
    <h3> </h3> 
    <p class= "scrollwork" id="portfolio"> scroll to work </p>  
  </div>
</section>


<div class="container middle">
//stuff here
</div>

<div class= "container bottom" id = "contact">
//stuff here
</div>





    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap-3.0.0/dist/js/bootstrap.min.js"></script>

  </body>

1 个答案:

答案 0 :(得分:3)

jQuery没有.replace函数,它只是字符串的本机方法,不适用于jQuery对象。

当您将ID作为字符串传递时,只需删除jQuery包装

function goToByScroll(id){

  id = id.replace("link", "");

  $('html,body').animate({
       scrollTop: $("#"+id).offset().top}, 'slow'
  );

}