Apply jquery propieties on new element created aft

2019-09-08 15:23发布

I have a problem with jquery and bootstraps modal. There's a page with a dynamic table and a modal that load remote content everytime is opened.

When I load the page for the first time everything works fine, but when I edit the table, to be more precise when I add or edit a row, the modal function stop working. In this cases the browser open directly the remote page, read_properties.php

This is how I call the modal, every row has a different id:

<a data-target="#id_target" href="read_properties.php?id=xx">

And this is the jQuery event that load remote content in to the modal (I found this solution here on Stackoverflow):

$("a[data-target=#id_target]").click(function(ev) {
  ev.preventDefault();
  var target = $(this).attr("href");

  $("#id_target .modal-body").load(target, function() { 
   $("#id_target").modal("show"); 
  });
});

Thanks to all!

2条回答
家丑人穷心不美
2楼-- · 2019-09-08 15:33

The solution was simple. I've edit the first line and use the .on event on the document body:

$(document.body).on('click', "a[data-target=#ads]", function(ev){
  ev.preventDefault();
  var target = $(this).attr("href");

  // load the url and show modal on success
  $("#ads .modal-body").load(target, function() { 
    $("#ads").modal("show"); 
  });
});
查看更多
Emotional °昔
3楼-- · 2019-09-08 15:39

Try this,

$("a[data-target=#id_target]").live(function(ev) {
  ev.preventDefault();
  var target = $(this).attr("href");

  $("#id_target .modal-body").load(target, function() { 
   $("#id_target").modal("show"); 
  });
});

Click will not be binded with dynamic html. So you need to use live listener.

查看更多
登录 后发表回答