DOM Update via jQuery Mobile

2

I'm having trouble updating an element, via jQuery. I'll summarize the codes:

HTML

<div data-role="header" data-position="fixed" data-tap-toggle="false">
    <a href="#nav-panel" data-icon="bars" data-iconpos="notext">Menu</a>
    <h1>Ranking</h1>
    <a id="btnPlayerName" href="#" class="ui-btn-right">Player</a>
</div>

<div data-role="content">
    <ul id="rankingList" data-role="listview"></ul>
</div>

JS

$(document).on('pageshow', '#pagRanking', function() {
    headerData();
})

function headerData() {
    if(sessionStorage.getItem('mbPlayerID') == null) {
        window.location.href="index.php";
    }
    $("#btnPlayerName").empty();
    lblPN  = '<span class="ui-btn-inner">';
    lblPN += '<span class="ui-btn-class">';
    lblPN += playerName;
    lblPN += '</span>';
    lblPN += '</span>';
    $("#btnPlayerName").append(lblPN);
}

Everything is OK with the session, but append does not work.

Any ideas?

    
asked by anonymous 29.01.2014 / 19:28

1 answer

1

The code you entered in the question is perfectly valid and works as expected.

Example running on JSFiddle

Considerations when we are performing this type of operations on IDs:

ID is unique:

As you are performing operations on an element from your id , in this case the #btnPlayerName , you must ensure that it is unique in the entire document, not only in what you are currently viewing on the screen.

Note that CSS classes can be repeated, IDs are used to identify a single element present throughout the document, see unique identifiers (English) .

Your problem

jQuery mobile was not being "burst" due to repeated IDs, but was operating in the first element with the id indicated that he found in the document, instead of being performing the operation were intended in element you wanted.

This is because you were able to see output of your code in conditions but there seemed to be no change in the DOM.

Unrelated, but you can simplify your code of the function headerData() by rewriting it as follows:

function headerData() {

    if(sessionStorage.getItem('mbPlayerID') == null) {
        window.location.href="index.php";
    }

    var $btnInner = $('<span/>', {class:"ui-btn-class"}), // criar span interior
        $btn      = $('<span/>', {class:"ui-btn-inner"}); // criar span exterior

    $btnInner.html(playerName).appendTo($btn);            // juntar tudo
    $("#btnPlayerName").html($btn);                       // aplicar dentro do elemento alvo
}

Example working in JSFiddle

    
29.01.2014 / 21:07