简体   繁体   English

无法在JQuery中设置变量的HTML

[英]Trouble setting the HTML of a variable in JQuery

What I've done is loaded some HTML from a file and I am attempting to modify some elements within that HTML. 我所做的是从文件加载一些HTML,我试图修改该HTML中的一些元素。

The initialization looks like this: 初始化如下所示:

var id = player_info["ID"];
$("#main_container").append(
    $("<div />").attr({class: "player_container", id: "player_" + id}).css("display", "none")
);

// Add all information to the player container
var player_container = $("#player_" + id);
player_container.load("player_layout.html");

With player_layout.html looking like this: 随着player_layout.html看起来像这样:

<div class="player_name">

</div>
<div class="player_chips">
    Chips:
    <br/>
    <span class='bidding'></span>/<span class='chips'></span>
</div>
<div class="player_stats">
    Wins / Losses
    <br/>
    <span class="wins"></span>/<span class="losses"></span>(<span class="total_games"></span>)
    <br/><br/>
    Chips Won / Chips Lost
    <br/>
    <span class="chips_won"></span>/<span class="chips_lost"></span>
</div>
<button class="player_won">Player Has Won</button>

I then want to modify some of the elements, specifically classes. 然后我想修改一些元素,特别是类。 An example of the way I was initially doing this is: 我最初这样做的一个例子是:

player_container.find(".player_name").text(player_info['username']);

This wasn't working so I then tried to switch find with children and text with html but that didn't seem to work. 这不起作用所以我然后尝试用html切换带有childrentext find ,但这似乎不起作用。 I then tried this: 然后我尝试了这个:

$('> .player_name', player_container).html(player_info['username']);

but that also didn't work. 但那也行不通。 I understand that I can use DOM to grab the childNodes and compare the class names but there are a lot of classes that need modifying and I'd also like to know if this is possible in JQuery. 我知道我可以使用DOM来获取childNodes并比较类名,但是有很多类需要修改,我也想知道这是否可以在JQuery中使用。 Thanks in advance for any help. 在此先感谢您的帮助。

You need to use complete callback method of .load() 你需要使用.load()完整回调方法

var player_container = $("#player_" + id);
player_container.load("player_layout.html",  function(){
    player_container.find(".player_name").text(player_info['username']);
});

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

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