简体   繁体   中英

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.

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:

<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. 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. Thanks in advance for any help.

You need to use complete callback method of .load()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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