2013-06-25 116 views
0

使用jQuery UI(w/jquery 1.9.1)。我有一個可排序的列表。我通過表單添加了dom元素。用戶點擊一個按鈕,會出現一個對話框。用戶在文本框中鍵入文本並點擊「添加頁面」。一個新的列表項目將追加到列表中。問題是該列表視圖不包含正確的CSS。jQuery UI LISTVIEW不刷新

繼承人的jsfiddle - >http://jsfiddle.net/RQKng/1/

之前,你按一下紅色按鈕,你可以在列表項之間單擊,並注意選中的列表項變爲藍色。但是,任何新項目都不會變成藍色。

我嘗試:

$('#pageList ul').trigger('create').listview('refresh'); 

但是我收到該 '對象沒有方法 「列表視圖」'

回答

1

1錯誤:問題是在這條線:

$('.page').click(function() { 
     $('.page').removeClass('selected'); 
     $(this).addClass('selected'); 
    }); 

2 :解決方法如下:jsFiddle

3:一些解釋:

因爲你有事先不知道的動態元素,所以你必須讓jQuery意識到這一點。從jQuery docs

事件處理程序僅綁定到當前選定的元素;在代碼調用.on()時,頁面上必須存在 。

你想要的是這樣的:

Delegated events have the advantage that they can process events from descendant 
elements that are added to the document at a later time. 

解決方案:

$('.item-list').on("click","li",function() { 
    $('.page').removeClass('selected'); 
    $(this).addClass('selected'); 
}); 
+0

出色答卷。謝謝! – Sanya

+0

Np,祝你好運:) – rusln