jQueryで動的に挿入した要素にonclickイベントをバインドしたい
しかし、バインドされた関数は実行されません。この例が機能しない理由と、適切に実行する方法をご指摘いただければ幸いです。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
<title>test of click binding</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
jQuery(function(){
close_link = $('<a class="" href="#">Click here to see an alert</a>');
close_link.bind("click", function(){
alert('hello from binded function call');
//do stuff here...
});
$('.add_to_this').append(close_link);
});
</script>
</head>
<body>
<h1 >Test of click binding</h1>
<p>problem: to bind a click event to an element I append via JQuery.</p>
<div class="add_to_this">
<p>The link is created, then added here below:</p>
</div>
<div class="add_to_this">
<p>Another is added here below:</p>
</div>
</body>
</html>
編集: メソッドが挿入される 2 つの要素が含まれるように例を編集しました。その場合、alert()
呼び出しは実行されません。(コメントで指摘してくれた @Daff に感謝します)
ベストアンサー1
これらのメソッドはすべて非推奨です。on
問題を解決するには、 メソッドを使用する必要があります。
動的に追加された要素をターゲットにしたい場合は、
$(document).on('click', selector-to-your-element , function() {
//code here ....
});
これは非推奨の.live()
メソッドを置き換えます。