0

我正在使用以下代码在 div 中加载单独的 .html 文档:

JS

 $('.thumbnail').click(function() {
 var idStr = ("project/"+$(this).attr('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'});

                });
    });
 });

HTML

<div class="thumbnail" id="atmotype.html">
<img src="image.whatever">
</div>

这一切都按预期工作,但我还想在您打开项目时附加一个 ID,并且还能够直接链接到所述内容(已经在 div 中展开)。我一直在尝试,但无法提出解决方案,据说我对 JS 的总体感觉很糟糕。

如果有人能告诉我这是如何工作的,我将不胜感激。

4

1 回答 1

0

现在,当您单击.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) {

于 2012-11-05T15:36:55.547 回答