There's a table to display data from XML using jQuery AJAX and I want to change the text and background's color on hover and click.
First time, when document ready, it requested data and received data.xml. The data displayed. The color changed.
Second time, when I click a button (RELOAD Button), it requested data and received data2.xml, the data displayed correctly. BUT..the color wont change.
It used different data source (data.xml and data2.xml) and different function (display_data(), parse_data(), and reload_data(), parse_new_data() ) just to make debugging more easy.
index.html:
- Code: Select all
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Lorem ipsum</title>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<table cellspacing="0">
<tbody>
<!-- data goes here -->
</tbody>
</table>
<button>TES</button>
</body>
</html>
script.js:
- Code: Select all
$(document).ready(function(){
// display data
display_data();
// change background when mouseover <-- NOT WORK WHEN reload_data() execute
set_background();
// reload data
reload_data();
});
function display_data()
{
$.ajax({
url: 'data.xml',
type: 'GET',
async: false,
dataType: 'xml',
success: parse_data
});
}
function parse_data(xml)
{
var tbody = '';
var id = 0;
$(xml).find("item").each(
function()
{
tbody += (' <tr id="' + id + '">\n');
tbody += (' <td>' + $(this).find("nama").text() + '</td>\n');
tbody += (' <td>' + $(this).find("kelamin").text() + '</td>\n');
tbody += ' </tr>\n';
id++;
}
)
$('table tbody').html(tbody);
}
function set_background()
{
$('table tbody tr').bind({
mouseenter: function()
{
$(this).toggleClass('hover');
},
mouseleave: function()
{
$(this).toggleClass('hover');
},
click: function()
{
$('table tbody').find('tr').each
(
function()
{
$(this).removeClass('active');
}
);
$(this).addClass('active');
}
});
}
function reload_data()
{
$('button').click(
function()
{
$.ajax({
url: 'data2.xml',
type: 'GET',
async: false,
dataType: 'xml',
success: parse_new_data
});
}
)
}
function parse_new_data(xml)
{
var tbody = '';
var id = 0;
$(xml).find("item").each(
function()
{
tbody += (' <tr id="' + id + '">\n');
tbody += (' <td>' + $(this).find("nama").text() + '</td>\n');
tbody += (' <td>' + $(this).find("kelamin").text() + '</td>\n');
tbody += ' </tr>\n';
id++;
}
)
$('table tbody').html(tbody);
}
You can view my codes at http://gadodag.comoj.com/

