【问题标题】:Difference between onclick() and .on('click',function())? [duplicate]onclick() 和 .on('click',function()) 之间的区别? [复制]
【发布时间】:2018-03-15 12:33:10
【问题描述】:
$(document).ready(function(){
  // Add smooth scrolling
  $('.button').children().onclick(function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
      // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;

      });
    } // End if
  });
});




$(document).ready(function(){
  // Add smooth scrolling to all links
  $('.button').children().on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

当我使用 onclick() 函数时,单击按钮时没有滚动效果;它只跳转到文章,没有任何滚动效果。

但是当我使用 on('click',function()) 有滚动效果。

这两者有什么区别?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:
  • .onclick() 是一个javascript函数
  • .click() 和 .on("click") 是 jQuery 函数,jQuery 在其函数中添加了更多功能。

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2016-01-21
    • 2012-02-25
    相关资源
    最近更新 更多