Reputation: 1
In jQuery, I created an HTML table dynamically and at the end, I add a click function to add a class from a loaded external css file. In the Chrome javascript console, I can see the class added correctly but the style (colors) do not change. It's like the stylesheet elements do not exist. I added a body style change just to prove it is in fact loading with the HTML page.
Here is the js function that creates the table:
function processGetCallback(data) {
var tableText;
$('#KenTest').empty();
tableText = "<table cellpadding=2><tr><th>ID</th><th>text</th><th>date</th></tr>";
$.each(data, function(i, DataRow) {
tableText = tableText.concat("<tr><td>" + DataRow.IDCol + "</td><td>" + DataRow.txtCol + "</td><td>" + DataRow.dtCol + "</td></tr>");
});
tableText = tableText.concat("</table>");
$('#KenTest').append(tableText);
$('#KenTest tr').click(function () {
$(this).addClass("hightlight");
});
}
Here is the CSS:
body {
background-color: lightgray;
}
td.highlight {
background-color: red;
color: white;
}
tr.highlight {
background-color: red;
color: white;
}
li.highlight {
background-color: red;
color: white;
}
And here is the HTML page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Test of jQuery Ajax</title>
<link href="stylesheet.css" rel="stylesheet" />
</head>
<body>
<h1>jQuery Ajax Test</h1>
<h2>Get Ken Test Data</h2>
<ul id="KenTest">
<li class="highlight">ID: 1, txtCol: xyz, dtCol:1/1/2015</li>
</ul>
<hr>
<button id="btnGetAll" onclick="CallGetAllAjax()">Get All Rows</button><button id="btnGet2" onclick="CallGetTwoAjax()">Get 2 Rows</button>
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script src="js\main.js" type="text/javascript"></script>
</body>
</html>
Upvotes: 0
Views: 646
Reputation: 1
I am not sure how long I stared at this and kept missing the typo :/ The js had the class named "hightlight" and the css had the class named "highlight". Doh!
Upvotes: 0
Reputation: 41143
Use the click
method in its delegated form.
You may rather use the .on()
method like
$('#KenTest').on("click", "tr", function () {
$(this).addClass("hightlight");
});
Upvotes: 1
Reputation: 204
The problem is that the elements to which you are binding the click event handler does not exist in DOM when the handler is registered.
Here's a similar question, and there's a good solution from Prestaul: How do you access newly appended HTML elements in jQuery
Upvotes: 1