0

I'm trying to make a page that loads results from an external PHP script and then dynamically adds buttons which when clicked takes you to the other pages. I figured I'd do this via a for loop that gets the number of pages from the PHP file (which I've omitted).

I have an additional function called test(pageNum) that takes in a page number parameter and gets the results and displays them in the table. That functions fine but whenever I load the page it seems to call the button click functions immediately. Could someone explain the issue here please?

$(document).ready(function() {
  test(1);

  $.get("link here", {
    op: "pages"
  }, function(data) {
    $("h1").html(data);
    for (var j = 1; j < data.length; j++) {
      (function() {
        var btn = $("<button>/", {
          type: 'button',
          text: j,
          on: {
            click: test(j)
          }
        });
        $('#buttons').append(btn);
      })(j);
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Luke Davis
  • 143
  • 7
  • 2
    The problem is because you're passing the *result* of `test(j)` to the `cilck` handler, not a function reference as you should be. Try `click: function() { test(j); }`. You can also avoid the need for the closure if you read the `text` (or better still a `data` attribute) from the clicked `button` element – Rory McCrossan Nov 29 '17 at 11:44
  • Your only function is `$(document).ready` – Pedram Nov 29 '17 at 11:44
  • You don't have to add click event to all the buttons that you appended. Give it a class. And use on delegated click event to fire click for that element – bipen Nov 29 '17 at 11:45

1 Answers1

2

This code:

on: {  click: test(j) }

sets your click event to the result of test(j) - ie calls it immediately.

Change this to

on: { click: function() { test(j) } }
freedomn-m
  • 27,664
  • 8
  • 35
  • 57