I am attempting to make a small browser game and am having trouble selecting elements that were added using .html()
in jQuery.
For the game, I use an HTML template system where templates are stored in templates/%name%.txt
. Then, to load a template, I use the following function.
function template(name) {
$.get("templates/" + name + ".txt", function(data) {
$(".content").html(data);
});
}
Here is an example of a template I would use:
<div class="title">
<!-- FILL -->
</div>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<button class="in-btn quit">Quit Game</button>
<button class="in-btn reset">Reset Game</button>
Now, in order for me to edit the title of the game when certain changes occur, I would use $(".title").html("Game - <span>Player Data Example</span>");
.
However, because the template is not truly part of the HTML on the page, I cannot select it using the regular selectors, $(".title")
returns no elements.
So, how could I select an element added using .html()
via jQuery?
There is already a way to handle events where, for example, <td>
has been added using .html()
:
$(document).on('click', 'td', function(){
// Do something...
});