JavaScript追加后不会触发

我正在尝试创build一个允许用户通过新窗口编辑input的表单。 PHP将处理input,然后用新值附加新input。 显然,当我尝试编辑附加的input时,JavaScript不会触发。 请指教我做错了什么。 这是我的html代码:

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('.races').click(function(e){ console.log("Inside Testing"); e.preventDefault(); var currID = this.id; var content = '<form id="theForm" action="ct.php" method="post"> Race: <input type="text" id="race" name="race"><button type="submit" onClick="OKClicked()">Click this!</button></form>'; childWin = window.open('', "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no"); toBeAdded = $(this).closest('div'); childWin.document.close(); childWin.document.write(content); popupRace = childWin.document.getElementById("race"); parentRace = document.getElementById(currID); transferValues(); }) }); function transferValues() { popupRace.value = parentRace.value; } function setValue(text) { childWin.close(); toBeAdded.parent().append(text); toBeAdded.remove(); } </script> </head> <body> <div> Name: <input type="text" name="name"> </div> <div> <div> <input type="hidden" name="race-0" value="Human" id="race-0"> <span>race: Human</span> <a href="javascript:void(0)" class="races" id="race-0">Edit</a> </div> </div> <div> Name: <input type="text" name="name"> </div> <div> <div> <input type="hidden" name="race-1" value="God" id="race-1"> <span>race: God</span> <a href="javascript:void(0)" class="races" id="race-1">Edit</a> </div> </div> </body> </html> 

这是我的PHP代码:

 <?php $postDataKey = array_keys($_POST); $text = ""; foreach ( $postDataKey as $currPostKey ) { $currValue = $_POST[$currPostKey]; $text .= '<div><input type="hidden" name="'.$currPostKey.'-1" value="'.$currValue.'" id="'.$currPostKey.'-1"><span>'.$currPostKey.': '.$currValue.'</span> <a href="javascript:void(0)" class="races" id="race-1">Edit</a></div>'; } echo ' <html> <head> <script> window.opener.setValue(\''.$text.'\'); </script> </head> </html> ' ; ?> 

jQuery仅在运行时才了解页面中的元素,所以添加到DOM中的新元素不能被jQuery识别。 为了对抗这个使用事件委托 ,从新添加的项目冒泡事件到jQuery在页面加载时运行的那个DOM中的一个点。 许多人使用document作为捕捉冒泡事件的地方,但是没有必要去把DOM树放在高位。 理想情况下, 您应该委托给页面加载时存在的最近的父代。

您可能需要更改事件处理程序,以便使用on()方法。

这是在老版本的jQuery中用live函数解决的,与bind函数相反。

  • bind函数将一个事件附加到所有匹配的元素,只要它们在执行时刻存在。 之后添加的任何元素都将被排除。
  • 即使元素是在指令执行后创build的, live也会将事件附加到任何匹配的元素上。

在当前版本的jQuery中, bindlive已被replace为onon()的默认行为就像bind 。 幸运的是,有一种方法可以使用,使其像live一样工作。

我写了一篇关于它的文章 ,它可以帮助你理解如何。

把它们加起来…

 // This behaves like `bind` $(".clickable").on("click", function(){...}); // This behaves like `live` $(".parent-element").on("click", ".clickable", function(){...}); 

所以,只要search所有可能的元素可能有的共同的父元素$(document)如果你不想太费劲,可以使用$(document) ),而且你是金。

方法上的jQuery是你正在寻找; 点击链接并查找委派的事件。

“委托事件的优点是,他们可以处理后来添加到文档中的后代元素的事件。”