2012-02-29 21 views
3

我一直在努力尋找一種方法來更改標題中的按鈕,而不會丟失格式。我想將帶刪除圖標的刪除按鈕更改爲帶有檢查圖標的完成按鈕。如何使用jQueryMobile刷新標題中的按鈕?

下面的代碼的縮寫版本:

<!DOCTYPE html> 
<html> 
    <head> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" /> 
    <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script> 
    <script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script> 
    <script type="text/javascript"> 
    function swapButton() { 
     $('#button').attr('data-icon', 'check').text('Done').trigger('create'); 
     $('#header').trigger('create'); 
    } 
    </script> 
    </head> 
    <body> 
    <div data-role="page"> 
     <div data-role="header" data-position="fixed" id="header"> 
     <a data-icon="delete" id="button" onclick="swapButton()">Delete</a> 
     <h1>Test Page</h1> 
     </div> 
     <div data-role="content"> 
     <p>Click on Delete to get Done button</p> 
     </div> 
    </div> 
    </body> 
</html> 

這改變了按鈕的文本正常,但所有的格式就會消失。

我試過在按鈕和標題上都用trigger('create')這個不行,我也試過.page()這個方法,我在其他地方讀過,我也試過.button()

我想不出別的東西要試。

回答

5

請問像這樣的工作:

JS

function swapButton() { 
    var b = $('#button'); 
    b.text('Done'); 
    b.buttonMarkup({ icon: "check" }); 
    b.button('refresh'); 
} 

JQM文件:

+0

是的,完美的作品!謝謝。 – user1228295 2012-02-29 07:31:30

+0

function swapButton(){ $('#button')。text('Done')。buttonMarkup({icon:'check'}); } – user1228295 2012-02-29 07:47:39

2

您可以更改窗口小部件,而無需刷新它,如果你只改變了正確的要素。

$('#button').click(function() { 

    //1. change the `data-icon` attribute of the link element 
    //2. then find the `.ui-icon` element and remove the "delete" icon class, then add the "check" icon class 
    //3. then traverse to the `.ui-btn-text` element (a sibling of the `.ui-icon` element) and change the text of the element there 
    $(this).attr('data-icon', 'check').find('.ui-icon').removeClass('ui-icon-delete').addClass('ui-icon-check').prev().text('New Text!'); 
});​ 

這將導致一個帶有不同圖標和文本的按鈕。

這裏是一個演示:http://jsfiddle.net/jasper/Pd6au/1/

這裏是你的代碼,它是由jQuery Mobile的初始化之後(這僅僅是一個 「刪除」 按鈕):

<a data-icon="delete" id="button" class="ui-btn-left ui-btn ui-btn-icon-left ui-btn-corner-all ui-shadow ui-btn-up-a" data-theme="a"> 
    <span class="ui-btn-inner ui-btn-corner-all"> 
     <span class="ui-btn-text">Delete</span> 
     <span class="ui-icon ui-icon-delete ui-icon-shadow"></span> 
    </span> 
</a> 

當你做這樣的事情:$('#button').text('new text'),您覆蓋了小部件的整個HTML結構,這就是爲什麼在更改按鈕文本時定位.ui-btn-text元素很重要。

+0

這也是 - 謝謝! – user1228295 2012-02-29 07:35:50

3

這是做一個簡單的方法:

<div data-role="header"> 
    <h1>Test Page</h1> 
    <a class="button ui-btn-left" data-icon="delete">Delete</a> 
    <a class="button ui-btn-left" data-icon="check" style="display:none">Done</a> 
</div> 

$("a.button").click(function(){ 
    $("a.button").hide().eq(1).show(); 
}); 

http://jsfiddle.net/clausparkhoi/p6ZzN/3/