现在,当您单击.thumbnail
元素时,它正在触发您的click()
事件并$(this).attr('id')
用于哈希/滚动。要使其在页面加载时运行,您可能应该将其拆分为一个单独的函数,该函数将 ID 作为参数,然后从您的click()
事件中调用此函数以及使用 in 中的参数进行通用页面加载location.hash
。
$(document).ready(function(){
if (location.hash.length>0){
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id){
var idStr = "project/"+ id + "#projectcontainer";
// rest of your code
}
更新:这是关于 js 的事情,在解释时它都是有道理的,但执行它是个婊子。无论如何,非常感谢您的帮助。根据您的解释,我得到的是:
$(document).ready(function() {
if (location.hash.length > 0) {
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id) {
var idStr = "project/" + id + "#projectcontainer";
$('#projectcontainer').animate({
opacity: 0
});
$('#projectcontainer').hide().load(idStr, function() {
$(this).slideDown(500).animate({
opacity: 1
}, function() {
$.scrollTo('#gohere', 800);
$('#close').fadeIn(500).css({
'display': 'block',
'height': '25px'
});
});
});
}
我试图摆弄闭包和我在错误测试 js 方面的任何最小经验,但我不断收到来自这一行的错误:function addHashAndScroll(id) {