简体   繁体   中英

JavaScript/jQuery How to do .click function properly?

I have some buttons generated dynamically based on form inputs selected:

$.each(fields, function (i, field) {
  var field_id = $('[name=' + field.name + ']').closest("fieldset").attr('id');
  $("#results").append('<button id="jumpToThisStep" data-id="'+field_id.replace('q','')+'">'+field.value+ ' ' +'</button>');
});

}

In my doc.ready function I have the following:

  $('#jumpToThisStep').click(function() {
    var jump_to = $(this).data('id');
    showStep(jump_to);
  });

HTML:

<button id="jumpToThisStep" data-id="0"> ... </button>
<button id="jumpToThisStep" data-id="1"> ... </button>
<button id="jumpToThisStep" data-id="2"> ... </button>

Upon inspecting the elements they all have the proper data-id binding. But the only one that fires is the first one. What is preventing the others from preforming their .click ?

You need to use event delegation here since your buttons are added dynamically so event delegation will help you to attach the click event to these newly created button:

$('#results').on('click', '.jumpToThisStep', function() {
    var jump_to = $(this).data('id');
    showStep(jump_to);
});

Also id is unique, you need to use class for your button instead.

HTML DOM id must be unique. use class instead of.

<button class="jumpToThisStep" data-id="0"> ... </button>
<button class="jumpToThisStep" data-id="1"> ... </button>
<button class="jumpToThisStep" data-id="2"> ... </button>

If you want to bind event on DOM which you add to document after document ready event, must to use event delegation .

$('#results').on('click', '.jumpToThisStep',function() {
    var jump_to = $(this).data('id');
    showStep(jump_to);
});

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