我制作了一个可嵌入的JavScript小部件,与我制作的WordPress插件进行了对话。基本上,小部件会调用一些定制的WP端点,并获得JSON,然后构建一个类别产品的提要。每次点击类别下钻通过一个新的API调用获得新的数据。
这一切都有效,耶,但我有一个非常长的时间试图找出如何使浏览器返回按钮工作。
请注意,我不在乎它是否可以是一个简单的散列表或其他,这不需要书签或谷歌爬行。
我找到的教程只是说pushState是一个对象,但是是什么呢?
我的点击处理程序看起来像这样,
$('#sqsl_products').on('click', '.ssla-embed-link', function( e ) {
e.preventDefault();
var link = $(this),
linkType = link.attr('data-link_type'),
linkId = link.attr('data-link_id');
switch( linkType ) {
case 'categories':
getCategories( linkId );
break;
case 'products':
getProducts( linkId );
break;
case 'product':
getProduct( linkId );
break;
}
});每一种情况都指向不同的ajax调用,该调用获取数据并输出数据,例如:
function getCategories( id ) {
$.ajax({
method: 'GET',
url: apiUrl + '/categories',
beforeSend: function() {
$(domTag).prepend('<div class="ssla-loading-top"></div>');
},
dataType: 'json',
data: { categories: id },
})
.done(function( response ) {
var catList = '<ul>';
var brand = response.brand;
$.each(response.data, function () {
catList += '<li><a data-link_type=' + this.type + ' data-link_id=' + this.id + ' class="ssla-embed-link" href="#' + this.id + '"><img src="'+this.image+'"/>' + this.name + '</a></li>';
});
catList += '</ul>';
$(domTag).removeClass().addClass( 'ssla-' + brand + ' ssla-categories' ).html(catList);
})
.fail(function( jqXHR ) {
var json = $.parseJSON(jqXHR.responseText);
$(domTag).removeClass().addClass('ssla-error').html(json.message);
console.log(jqXHR);
});
}现在,pushState会出现在.done()链中吗?如果是的话,那么会添加什么呢?
任何提示都是非常感谢的,谢谢!
更新
让它起作用了-用这个
$(window).on('hashchange', function( e ) {
var hash = document.URL.substr(document.URL.indexOf('#')+1);
var split = hash.split('-');
if ( split.length < 2 ) {
return;
}
var linkType = split[0];
var linkId = split[1];
console.log(linkType);
console.log(linkId);
switch( linkType ) {
case 'categories':
getCategories( linkId );
break;
case 'products':
getProducts( linkId );
break;
case 'product':
getProduct( linkId );
break;
}
});但是,当返回到“第一页”时会失败。这是因为它不是通过散列来处理的,而是最初通过文档准备好上的ajax调用加载的吗?
发布于 2017-04-26 17:36:39
步骤1:添加window.location.hash = "#categories-" + id;而不是开关语句。
/*switch (linkType) {
case 'categories':
getCategories(linkId);
break;
case 'products':
getProducts(linkId);
break;
case 'product':
getProduct(linkId);
break;
}*/
//Replace the switch function. This will update the url to something like #categories-1 which will fire the event below
window.location.hash = '#' + linkType + '-' + linkId;
//Optionally, you can just set the href of the URL's to #categories-1 instead of using this function at all.步骤2:添加一个onhashchange处理程序,它将在任何时候触发哈希(即。#类别-1)URL中的更改:
$(window).on('hashchange', function( e ) {
let split = window.location.split('-');
if ( split.length < 2 )
return;
var linkType = split[0];
var linkId = split[1];
switch( linkType ) {
case 'categories':
getCategories( linkId );
break;
case 'products':
getProducts( linkId );
break;
case 'product':
getProduct( linkId );
break;
}
}https://stackoverflow.com/questions/43640867
复制相似问题