Apply jquery propieties on new element created after the page is loaded

自作多情 提交于 2019-12-25 05:35:10

问题


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!


回答1:


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.




回答2:


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"); 
  });
});


来源:https://stackoverflow.com/questions/20617477/apply-jquery-propieties-on-new-element-created-after-the-page-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!