简体   繁体   English

带有按钮Onclick功能的jQuery

[英]Jquery With Button Onclick Function

I'm just starting web development, and have a function loadTweets that pulls from another file and displays, and when I get rid of the button, and just run it directly as an anonymous function it works, however, for some reason the button does not work to call the function. 我刚刚开始Web开发,并且具有从另一个文件中提取并显示的loadTweets函数,当我删除该按钮并直接将其作为匿名函数运行时,它可以工作,但是由于某种原因,该按钮确实不能调用该函数。

Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!

<html>
  <head>
    <script src="jquery.js"></script>
    <script src="data_generator.js"></script>

  </head>
  <button type = "button" onclick="loadTweets"> Load </button>
  <body>
    <script>
      $(document).ready(function(){
        var loadTweets = function(){
          var $body = $('body');
          $body.html('');
          var index = streams.home.length - 1;
          while(index >= 0){
            var tweet = streams.home[index];
            var $tweet = $('<div></div>');
            $tweet.text('@' + tweet.user + ': ' + tweet.message);
            $tweet.appendTo($body);
            index -= 1;
          }
        }
      });
    // });



    </script>
  </body>
</html>

You need define the function outside the document-ready handler and to use () with function 您需要在文档就绪处理程序之外定义函数,并在函数中使用()

<button type = "button" onclick="loadTweets()"> Load </button>

<script>
  var loadTweets = function(){
      //
  });
</script>

However I would suggest you to use unobtrusive event handler. 但是我建议您使用不显眼的事件处理程序。

HTML , Add an ID attribute to button HTML ,向按钮添加ID属性

<button type="button" id="loadTweets"> Load </button>

Script , then use ID selector to target the element and .on() to bind event handler. 脚本 ,然后使用ID选择器定位元素,并使用.on()绑定事件处理程序。

$(document).ready(function () {
    var loadTweets = function () {
        //existing code
    }

    $('#loadTweets').on('click', loadTweets)
});

You can use in another way 您可以以其他方式使用

<html>
  <head>
    <script src="jquery.js"></script>
    <script src="data_generator.js"></script>

  </head>
  <body>
  <button type = "button" onclick="loadTweets()"> Load </button>
    <script>
        function loadTweets(){
          var $body = $('body');
          $body.html('');
          var index = streams.home.length - 1;
          while(index >= 0){
            var tweet = streams.home[index];
            var $tweet = $('<div></div>');
            $tweet.text('@' + tweet.user + ': ' + tweet.message);
            $tweet.appendTo($body);
            index -= 1;
          }
        }
    </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM