0

我试图让这个条件语句起作用,但没有运气

<body onload="HashTagInsert()">
    function HashTagInsert() {
        var hash="window.location";
        if (hash==="http://www.address.com#anchor1") 
        {
            document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
        }
        else if (hash==="http://www.url.com/foler/code/page.html#anchor2")
        {
            document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
        }
        else ()
        {
            document.getElementById("insert-text").innerHTML="something else text"
        }
    }
</body>
4

3 回答 3

0

不要在 window.location 周围添加引号。

var hash = window.location.href;
于 2013-08-21T12:50:35.303 回答
0

如果要将当前窗口位置与某些字符串进行比较,则需要正确设置“哈希”变量:

var hash = window.location;

但我不确定我是否遇到了你的问题。如果您的 javascript 无法正确设置您的 html,则还有时间问题。这取决于您的javascript何时被调用。在渲染 DOM 之前或之后。因为如果你的 javascript 在你的 DOM(和你的元素'#insert-text')被渲染之前执行,你将无法选择这个 DOM 元素。

而且......但这也许只是我的观点,在你的代码中有大量的 if / else if / else 结构是很不酷的。

您可能想要映射一些 url 和文本,这样您就不需要让您的生活变得更加艰难。

例如:

var html;
var mapping = {
    "http://www.address.com#anchor1":"<h2>Yeah</h2><p>Baby</p>",
    "http://www.address.com#anchor2":"<h2>Cool</h2><p>Tomato</p>",
    "default": "<h2>Woops</h2><p>Honolulu rocks</p>"
}

mapping[window.location.href] ? html = mapping[window.location.href] : html = mapping['default'];

document.getElementById("insert-text").innerHTML=html;
于 2013-08-21T13:29:25.443 回答
0

如果您希望hash变量成为window.location对象的值,则不要在对象名称周围加上引号,因为这会将其转换为字符串文字。

 var hash = window.location;

我建议不要调用该变量hash,因为它可能与window.location.hash包含 URL 的片段 ID 组件的 混淆。

于 2013-08-21T12:49:19.767 回答