0

在这个小提琴中,按钮被动态地附加到一个循环中。如何更新代码以便每个按钮在循环中只添加一次而不是多次?我认为这是因为克隆方法?

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

小提琴代码:

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

});​
4

1 回答 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);
    }
});​

演示

或者

$(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));
    }
});

演示

在您的代码clone()方法中,复制所有a标签中存在的所有标签#links

于 2012-07-19T09:16:54.660 回答