简体   繁体   English

如何选择在jQuery中使用.html()添加的HTML元素

[英]How to Select HTML Elements Added Using .html() in jQuery

I am attempting to make a small browser game and am having trouble selecting elements that were added using .html() in jQuery. 我正在尝试制作一个小型浏览器游戏,无法选择在jQuery中使用.html()添加的元素。

For the game, I use an HTML template system where templates are stored in templates/%name%.txt . 对于游戏,我使用HTML模板系统,其中模板存储在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>"); 现在,为了使我可以在发生某些更改时编辑游戏标题,我将使用$(".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. 但是,由于模板并不是页面上HTML的真正组成部分,因此无法使用常规选择器选择它, $(".title")返回任何元素。

So, how could I select an element added using .html() via jQuery? 那么,如何选择通过jQuery使用.html()添加的元素?

There is already a way to handle events where, for example, <td> has been added using .html() : 已经存在一种处理事件的方法,例如,使用.html()添加了<td>

$(document).on('click', 'td', function(){ 
    // Do something...
});

why don't you use $(".content").load("templates/" + name + ".txt") to load? 为什么不使用$(".content").load("templates/" + name + ".txt")进行加载?

And you can still select and add listener using delegation. 而且,您仍然可以使用委派来选择和添加侦听器。 also you can perform something after the view gets populated if you pass another callback as second argument of load(..., <callback>) . 如果将另一个回调作为load(..., <callback>)第二个参数传递,则在填充视图之后也可以执行某些操作。

And to add more if a content is there in DOM (dosen't matter how it was added, with html(..) or by a dom appendChild method) you can always select it (at the time of its presence). 如果要在DOM中添加内容,则要添加更多内容(与添加内容无关,可以使用html(..)或通过dom appendChild方法添加),您始终可以(在存在时)选择它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM