无法在JQuery中设置变量的HTML

时间:2016-12-30 09:24:51

标签: javascript jquery html

我所做的是从文件加载一些HTML,我试图修改该HTML中的一些元素。

初始化如下所示:

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");

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>

然后我想修改一些元素,特别是类。我最初这样做的一个例子是:

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

这不起作用,所以我尝试将findchildrentext切换为html,但这似乎不起作用。然后我尝试了这个:

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

但这也行不通。我知道我可以使用DOM来获取childNodes并比较类名,但是有很多类需要修改,我也想知道这是否可以在JQuery中使用。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您需要使用.load()

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