Javascript变量等于特定URL
我试图让这个条件语句起作用,但运气不好Javascript变量等于特定URL,javascript,url,if-statement,anchor,Javascript,Url,If Statement,Anchor,我试图让这个条件语句起作用,但运气不好 <body onload="HashTagInsert()"> function HashTagInsert() { var hash="window.location"; if (hash==="http://www.address.com#anchor1") { document.getElementById("insert-text").innerHTML=
<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>
函数HashTagInsert(){
var hash=“window.location”;
如果(哈希==”http://www.address.com#anchor1")
{
document.getElementById(“插入文本”).innerHTML=“Title正文文本””;
}
else if(散列==”http://www.url.com/foler/code/page.html#anchor2")
{
document.getElementById(“插入文本”).innerHTML=“Title正文文本””;
}
else()
{
document.getElementById(“插入文本”).innerHTML=“其他文本”
}
}
如果希望散列
变量成为窗口位置
对象的值,则不要在对象名称周围加引号,因为那样会将其转换为字符串文字
var hash = window.location;
但是我建议不要调用变量
hash
,因为这可能会与window.location.hash
混淆,后者包含URL的片段ID组件。不要在window.location周围添加引号
var hash = window.location.href;
如果要将当前窗口位置与某个字符串进行比较,则需要正确设置“hash”变量:
var hash = window.location;
但我不确定我是否了解你的问题。
如果您的javascript无法正确设置html,那么还存在计时问题。这取决于javascript何时被调用。在呈现DOM之前或之后。因为如果在呈现DOM(以及元素“#insert text”)之前执行javascript,则无法选择此DOM元素
而且。。。但这可能只是我的观点,在代码中有大量if/elseif/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;
var-html;
变量映射={
"http://www.address.com#anchor1“:“是的,宝贝”,
"http://www.address.com#anchor2“:“凉快的西红柿”,
“默认值”:“Woops火奴鲁鲁岩石”
}
映射[window.location.href]?html=mapping[window.location.href]:html=mapping['default'];
document.getElementById(“插入文本”).innerHTML=html;
hash将等于“window.location”而不是URL?