简体   繁体   中英

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.

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

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

Script , then use ID selector to target the element and .on() to bind event handler.

$(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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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