Friday, May 28, 2010

jQuery Rebind After Ajax Call

Hampir 2 jam lamanya, gw muter2 di coding
JAVASCRIPT. Bingung kenapa innerHTML yg
di "isi" oleh AJAX yg terdapat sisipan
JAVASCRIPT ga jalan.Nah utk lebih jelas nya
silahkan dicuba code di bawah ini.
Sebelumnya pastikan jQuery sudah
ter-"install" jika belum silahkan download
di sini Download jQuery.
<!-- file: index.html -->
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="test1">
Mouse over me please
</div>
<div id="data-container">
</div>
</body>
<script type="text/javascript">
$('#test1').mouseover(function(){

alert('test1 triggered');

$.post('data.html',function(data){

$('#data-container').html(data);
});
});
</script>
</html>
<!-- end of: index.html -->

<!-- file: data.html -->
<div id="test2">Request Complete, try mouse over to trigger alert</div>
<script type="text/javascript">
$('#test2').mouseover(function(){

alert('test2 triggered');
});
</script>
<!-- end of: data.html -->
Humm... aneh kan? Fungsi alert seakan2 tidak
tereksekusi. Nah solusi nya di cuba code
di bawah ini.
<!-- file: index.html -->
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="test1">
Mouse over me please
</div>
<div id="data-container">
</div>
</body>
<script type="text/javascript">
$('#test1').mouseover(function(){

alert('test1 triggered');

$('#data-container').load('data.html',function(data){

// Re-Bind
$('#test2').mouseover(function(){

alert('test2 triggered');
});
});
});
</script>
</html>
<!-- end of: index.html -->

<!-- file: data.html -->
<div id="test2">Request Complete, try mouse over to trigger alert</div>
<!-- end of: data.html -->
Semoga membantu.
Coding for life, coding with ethic.

No comments: