绑定到动态创建的iframe中的元素


Bind to element in dynamically created iframes

我有一个页面,用户可以在其中创建多个iframe。

用户点击链接创建新的iframe:

父页面:

 echo "<div id='iframes_wrapper'>";
 $q = mysql_query("SELECT * FROM chat_iframe WHERE init_uid='$_SESSION[uid]'");
 while ($row = mysql_fetch_assoc($q)) {
  $target_uid = $row['target_uid'];  
  $iframeid = $row['id'];
  echo "<iframe id='iframe_$iframeid' src='includes/chat_iframe.php?iframeid=$iframeid' class='chat_iframe' scrolling='no' frameborder='0' data-target_uid='$target_uid'></iframe>";
 }
 echo "</div>";
$(document).ready(function() { 
  $("#window").delegate(".open_iframe","click", function() { 
    var target_uid = $(this).attr("data-uid"); 
    $.post("processforms/process_chat.php", { target_uid:target_uid, open_iframe_submit:0 }, function() {
     $("#iframes_wrapper").load('chat.php?timer='+new Date().getTime() + " #iframes_wrapper", function() {
         $("iframe").each(function() {
           var this_iframeid = $(this).attr("id");
           console.log(this_iframeid);
           $("#iframe_"+this_iframeid).contents().find("a").on('click', function(event) { alert('test'); });
         });
        return false;
     });
    });
  });
  return false;
});  

iframe.php

 echo "$target_displayname <a href='javascript:void(0);' data-iframeid='$iframeid' class='close_chat_iframe'><i class='fa fa-remove' style='float:right;'></i>";

我遇到的问题是,当用户点击iframe中的链接时,什么都不会发生。

您应该尝试而不是$("iframe").each(function() {...});:

$("iframe", this).on('load', function () {...});