在页面加载时运行JS函数


Run a JS function on page load

我知道这个问题已经被问过很多次了,但我的情况不同。因此,我有一个外部JavaScript文件,其中包含accordion menus的代码(您知道,用户单击标题并展开)。现在我想从url中获得#(哈希符号),并根据它打开一个特定的"手风琴"onload。下面是我尝试过的:

<body onload="runAccordion(index);"> <!-- In the example bellow, index should be equal to 1 -->

但它从来没有工作(如所希望的),因为我不知道如何"读取"url的#(元素的id)…下面是手风琴的标记:

<div id="AccordionContainer" class="AccordionContainer">
    <div onclick="runAccordion(1);">
        <div class="AccordionTitle" id="AccordionTitle1">
            <p>Title</p>
        </div>
    </div>
    <div id="Accordion1Content" class="AccordionContent">
        <p>
<!-- Content -->
        </p>
    </div>
或者我应该使用PHP $_GET ??

JS文件内容:

var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
    var nID = "Accordion" + index + "Content";
    if (openAccordion == nID)
        nID = '';
    setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
    openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;
    var opening = (openingId == '') ? null : document.getElementById(openingId);
    var closing = (closingId == '') ? null : document.getElementById(closingId);
    if (timeLeft <= elapsedTicks) {
        if (opening != null)
            opening.style.height = ContentHeight + 'px';
        if (closing != null) {
            closing.style.display = 'none';
            closing.style.height = '0px';
        }
        return;
    }
    timeLeft -= elapsedTicks;
    var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
    if (opening != null) {
        if (opening.style.display != 'block')
            opening.style.display = 'block';
        opening.style.height = (ContentHeight - newClosedHeight) + 'px';
    }
    if (closing != null)
        closing.style.height = newClosedHeight + 'px';
    setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}

试一下:

$(document).ready(function() {
    var hash = window.location.hash;
    hash = hash.length > 0 ? hash.substring(1);
    if (hash.length) {
        runAccordion(window.location.hash);
    }
});

上面的代码将从URL中获取哈希索引。要向URL添加散列,请尝试以下操作:

window.location.hash = 1; //or whatever your index is
# You can use: #
window.onload = function() {
    runAccordion(window.location.hash);
}