0

myApp.jsが次のように含まれているhtmlページを開きます。

<html>
<body>
......
<div id="dynamicForm"></div>
......
<script type="text/javascript" src="myPath/myApp.js"></script>
......
</body>
</html>

次に、myApp.jsで定義されたフォームをこのhtmlページ( "#dynamicForm")に動的にロードしたいのですが、myApp.jsには次のような行があります。

.....
//load the form on the html page
$('#dynamicForm').html(createDynamicForm()).show();         
.....
//the function creating the form
function createDynamicForm(){
  var jqForm=$('<form id="dynamicFormId">'
  ......
  + '<button id="btn">OK</button>'
  + '</form>');
  $('body').append(jqForm);
  return jqForm;
}
.....
//click the button on the form to trigger the alert box
("#btn").click(function(){
    alert("you click the button");
});

フォームをhtmlページにロードできますが、この動的にロードされたフォームで[OK]ボタンをクリックしても、アラートがポップアップしません。これは、動的フォームの前にmyApp.jsにhtmlページがロードされているためと思われます。が作成されると、「クリック」イベントは、フォームを作成するmyApp.jsで定義されたハンドラーでは処理できません。どうすればこの問題を解決できますか?

4

1 に答える 1

3

動的に試行している#btnため、デリゲートイベントハンドラーが必要であり、そのためにはを使用する必要があります.on()

$('body').on('click', '#btn', function(){
    alert("you click the button");
});

forデリゲートイベントの構文は次の.on()ようになります。

$(staticElement).on( eventName, target, handlerFunction );

ここでは、staticElementページの読み込み時にDOMに属する要素、つまり動的ではない要素を指します。

于 2012-06-29T11:40:24.480 に答える