在页面加载时运行JS函数

时间:2014-05-17 13:00:27

标签: javascript php jquery html get

我知道这个问题已被多次询问,但我的情况有所不同。所以我有一个外部JavaScript文件,其中包含我accordion menus的代码(您知道,用户点击标题并进行扩展)。现在我想从网址获取#(哈希符号)并根据它打开特定的“手风琴”onload。 所以这就是我尝试过的:

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

但它从未奏效(按需要),因为我不知道如何“读取”网址#(元素的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);
}

2 个答案:

答案 0 :(得分:2)

尝试以下内容:

$(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

答案 1 :(得分:0)

# You can use: #

window.onload = function() {
    runAccordion(window.location.hash);
}