JQuery Mobile: принудительное обновление содержимого
У меня большая проблема: у меня есть listview
, и каждый элемент ссылается на страницу #concorsi
. Когда я нажимаю ссылку, URL становится #concorsi?numero=1
, потому что я получаю форму номер 1 из JSON.
Когда я нажимаю первый раз, все ОК. Каждый вход визуализируется с помощью классов jQuery Mobile, но если я вернусь и после перехода в ту же ссылку, код не обновится.
Заголовок хорошо визуализирован, но нет. Как я могу принудительно обновить содержимое div?
Это мои функции JavaScript:
<script type="text/javascript">
$(document).bind( "pagebeforechange", function( e, data ) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if ( typeof data.toPage === "string" ) {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
var u = $.mobile.path.parseUrl( data.toPage ),
re = /^#concorso/;
if ( u.hash.search(re) !== -1 ) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showConcorso( u, data.options);
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
</script>
И showConcorso()
L
function showConcorso( urlObj, options )
{
document.getElementById('conccont').innerHTML="";
var concorsoNum = urlObj.hash.replace( /.*numero=/, "" ),
// Get the object that represents the category we
// are interested in. Note, that at this point we could
// instead fire off an ajax request to fetch the data, but
// for the purposes of this sample, it already in memory.
concorso = obj.concorsi[ concorsoNum ],
// The pages we use to display our content are already in
// the DOM. The id of the page we are going to write our
// content into is specified in the hash before the '?'.
pageSelector = urlObj.hash.replace( /\?.*$/, "" );
if ( concorso ) {
// Get the page we are going to dump our content into.
var $page = $( pageSelector ),
// Get the header for the page.
$header = $page.children( ":jqmData(role=header)" ),
// Get the content area element for the page.
$content = $page.children( ":jqmData(role=content)" ),
$footer = $page.children( ":jqmData(role=footer)" );
// Find the h1 element in our header and inject the name of
// the category into it.
$header.find( "h1" ).html(concorso['title']);
markup=document.createElement('form');
markup.setAttribute('action','#home');
markup.setAttribute('method','POST');
markup.id="concForm";
markup.onchange="alert (test)";
items=obj.concorsi[concorsoNum].elementi;
for(field in items) {
nest=items[field];
nest=obj.campi[nest];
switch(nest.type){
case "free": markup.appendChild(createFree(nest));
break;
case "text": markup.appendChild(createText(nest));
break;
case "textarea": markup.appendChild(createTextArea(nest));
break;
case "switch": markup.appendChild(createSwitch(nest));
break;
case "switchcust": markup.appendChild(createSwitchCustom(nest));
break;
case "slider": markup.appendChild(createSlider(nest));
break;
case "select": markup.appendChild(createSelect(nest));
break;
case "checkbox": markup.appendChild(createCheckbox(nest));
break;
case "radio": markup.appendChild(createRadio(nest));
break;
case "reset": markup.appendChild(createButton(nest));
break;
case "submit": markup.appendChild(createButton(nest));
break;
}
}
// Inject the category items markup into the content element.
$content.html( markup );
// Pages are lazily enhanced. We call page() on the page
// element to make sure it is always enhanced before we
// attempt to enhance the listview markup we just injected.
// Subsequent calls to page() are ignored since a page/widget
// can only be enhanced once.
$page.page();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage( $page, options );
}
}
Ответы
Ответ 1
Чтобы обновить пользователя страницы:
.trigger('create');
Подробнее здесь:
Создать против обновления: важное различие
Обратите внимание, что существует важное различие между методом создания события и обновления, который некоторые виджеты. Событие создания подходит для улучшения сырой разметки который содержит один или несколько виджетов. Необходимо использовать метод обновления на существующих (уже усиленных) виджетах, которые были обработаны программно и необходимо обновить пользовательский интерфейс, чтобы он соответствовал.
Например, если у вас есть страница, на которой вы динамически добавили новую неупорядоченный список с атрибутом data-role = listview после создания страницы, инициирование создания в родительском элементе этого списка будет преобразовывать его в виджет в стиле списка. Если больше элементов списка было тогда с программным добавлением, вызов метода обновления списка просмотров обновите только эти новые элементы списка в расширенном состоянии и оставьте существующие элементы списка нетронутые.
Вы также можете обновить список, например:
$('#mylist').listview('refresh');
Подробнее здесь:
Обновление списков
Если вы добавляете элементы в список, вам нужно вызвать метод refresh(), чтобы обновить стили и создать вложенные списки, которые добавлены. Например:
$('#mylist').listview('refresh');
Обратите внимание, что метод refresh() влияет только на новые узлы, добавленные к список. Это делается по соображениям производительности. Любые элементы списка уже обновление будет проигнорировано процессом обновления. Это означает, что если вы изменяете содержимое или атрибуты в уже расширенном списке элемент, они не будут отражены. Если вы хотите, чтобы элемент списка обновлялся, замените его свежей разметкой перед вызовом обновления.
Обновление элементов формы:
Освежающие элементы формы
В jQuery Mobile некоторые расширенные элементы управления формой просто вставляются (входы), но другие настраиваются элементы управления (выбирает, ползунки), созданные и синхронизированные с собственный контроль. Чтобы программно обновить элемент управления формой с помощью JavaScript, сначала управляйте встроенным элементом управления, затем используйте обновление метод, чтобы сообщить расширенному элементу управления обновить себя в соответствии с новым государство. Вот несколько примеров того, как обновлять общие элементы управления формой, затем вызовите метод обновления:
Флажки:
$("input[type='checkbox']").prop("checked",true).checkboxradio("refresh");
Радиоприемники:
$("input[type='radio']").prop("checked",true).checkboxradio("refresh");
Selects:
var myselect = $("#selectfoo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
Слайдеры:
$("input[type='range']").val(60).slider("refresh");
Переключатели (они используют слайдер):
var myswitch = $("#selectbar");
myswitch[0].selectedIndex = 1;
myswitch.slider("refresh");
Складная:
$('div[data-role=collapsible]').collapsible();