0

In this fiddle buttons are appended to dynamically within a loop. How can the code be updated so that that each button is added just once in the loop instead of multiple times ? I think this is because of the clone method ?

http://jsfiddle.net/8JXTT/9/

Fiddle code :

<div data-role="page" id="firstpage">

        <div data-role="header">
                <h1>First Page</h1>
        </div>

<div data-role="content" id="links">
        <a href="#secondpage" data-role="button">Link button</a>
</div>

        <div data-role="footer">
                <h4>Page Footer</h4>
        </div>

</div>

<div data-role="page" id="secondpage">

        <div data-role="header">
                <a href='#' class='ui-btn-left' data-icon='arrow-l' onclick="history.back(); return false">Back</a><h1>Bar</h1><a href="#firstpage">home</a>
        </div>

        <div data-role="content">
                <p>I'm first in the source order so I'm shown as the page. (this is secondpage)</p>
                <p><a href="#thirdpage">Go to third page</a></p>
        </div>

        <div data-role="footer">
                <h4>Page Footer</h4>
        </div>
</div>
​
$(document).ready(function() {

    for (var i = 0; i < 4; i++) {
    var linkButton = $('#links a').clone(true);
    linkButton.find('span.ui-btn-text').text('Link Button2');
    $('#links').append(linkButton);
}

});​

1 Answer 1

1
$(document).ready(function() {
    for (var i = 0; i < 4; i++) {
      var linkButton = $('#links a:first').clone(true); // clone first one only
      linkButton.find('span.ui-btn-text').text('Link Button2');
      $('#links').append(linkButton);
    }
});​

Demo

OR

$(document).ready(function() {
    var linkButton = $('#links a').clone(true); // keep reference outside of loop
    for (var i = 0; i < 4; i++) {
      linkButton.find('span.ui-btn-text').text('Link Button2');
      $('#links').append(linkButton.clone(true));
    }
});

Demo

In your code clone() method make copy of all a tag exists in the #links in each turn.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks but what if there is not link button already on the page, like in this fiddle : jsfiddle.net/8JXTT/16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.