2011-06-23 81 views
0

我有一個小問題,我不知道它來自哪裏。 我使用jQuery UI(當然jQuery的)Jquery UI中的按鈕有一些標籤變化的問題

我有以下HTML:

<input type="checkbox" id="test" value="test"/> 
    <label for="test">Show Test</label> 
    <div id="checkedDiv"></div> 

及以下JS:

function clickChange() { 
    var currentText = this.nextSibling.innerHTML; 
    this.nextSibling.innerHTML = 
    (this.checked) ? currentText.replace("Show","Hide") : 
        currentText.replace("Hide", "Show"); 
    $("#checkedDiv").text(this.nextSibling.innerHTML); 
} 

var test=document.getElementById("test") 
test.onclick=clickChange; 
$("#test").button(); 

的問題是,在第一次點擊,innerHTML不會改變。之後,它的作品。 爲了讓人有點失望,nextSibling似乎改變了(至少從#checkedDiv中看到的是),但沒有出現在firefox/firebug上的DOM Tree上。

我錯過了什麼嗎?

感謝 (如果你想自己嘗試一下,它在這裏:http://jsfiddle.net/nvNKW/3/

編輯:

的(或至少一個)解決方案是使用標籤阿齊茲·謝赫的建議:

function clickChange() { 
    var currentText = $(this).button("option","label"); 
    $(this).button("option","label",(this.checked)? currentText.replace("Show","Hide") : currentText.replace("Hide", "Show")); 
} 

並且沒有必要更改html或按鈕初始化。

+0

的觀察,如果你註釋掉$( 「#測試」)按鈕()。那麼你的代碼似乎很好。 –

+0

是的,我注意到,這可能是jQuery UI引入了一些破壞它的東西。 –

回答

1

請嘗試使用$("#test").button({ label: newText });代替this.nextSibling.innerHTML

編輯標籤:所以你的固定JS函數是:

function clickChange() { 
    var currentText = this.nextSibling.firstChild.innerHTML; 
    var newText = (this.checked) ? currentText.replace("Show","Hide") : currentText.replace("Hide", "Show"); 
    $("#test").button("option", "label", newText); 
    $("#checkedDiv").text(this.nextSibling.innerHTML); 
} 
+0

使用標籤選項似乎可以解決問題(但代碼不完全是這樣,我用正確的代碼編輯了問題)。 –

+0

感謝您優化固定代碼。 –

0

這是因爲nextSibling()也返回文本節點。您正在更改輸入後的空白空白空間,而不是下一個標記。

的jQuery很容易,做

$(this).next('label').html() 
+0

這段代碼產生的結果與我在我的問題中得到的結果相同(即第一次更改似乎不會影響按鈕,但是其他的做法) –