简体   繁体   English

如何使用url中的#运行javascript函数?

[英]How to run a javascript function using the # in the url?

hi this all started when i ran a function (lets call it loadround) that altered the innerHTML of an iframe. 嗨,当我运行一个更改了iframe的innerHTML的函数(让我们称之为loadround)时,一切就开始了。 now once loadframe was loaded there were links in the iframe that once clicked would change the iframe page. 现在,一旦加载了loadframe,iframe中就会存在一些链接,单击这些链接将更改iframe页面。 the only problem is when i click the back button the loadround page was gone. 唯一的问题是,当我单击后退按钮时,loadround页面消失了。 i've thought about this numerous times to no avail. 我已经无数次地想到了这一点。 so i tried this code. 所以我尝试了这段代码。

<a href="javascript:void(loadround('parameter1','parameter2'))">loadround</a>

then 然后

function loadround(a,b){
window.location.hash = "#loadround('"+a+"','"+b+"')";

var code = "<(h2)>"+a+"</(h2)><(h2)>"+b+"</(h2)>"
   var iFrame =  document.getElementById('iframe');
   var iFrameBody;
   iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0]
  iFrameBody.innerHTML = code;
 }

(the brackets in the h2 are intentional) then i would try to reload the function by possibly an onload function but for now i was testing with a simple href as followed. (h2中的括号是有意的),那么我将尝试通过可能的onload函数来重新加载该函数,但目前我正在按照以下简单href进行测试。

function check(){
var func = location.hash.replace(/#/, '')
void(func);
}
<a href="javascript:check()">check</a>  

unfortunately the check code doesn't work and im almost certain there is an easier way of doing this. 不幸的是,检查代码不起作用,并且几乎可以肯定的是,有一种更简单的方法可以执行此操作。 i tried changing the src of the iframe instead of the innerhtml and there was the same problem. 我尝试更改iframe的src而不是innerhtml,并且出现了相同的问题。 thanks in advance 提前致谢

You are misunderstanding the function void , which just make sure the return value is undefined. 您误解了函数void ,只是确保返回值未定义。 That prevents the browser from navigating away when you put it in a link. 当您将其放在链接中时,这可以防止浏览器离开。 You can test that yourself by pasting the next addresses in your browser: 您可以通过在浏览器中粘贴下一个地址来测试自己:

javascript:1        // note: return value 1, browser will print "1" on screen
javascript:void(1)  // note: undefined return value, browser won't navigate away

It's strongly discouraged to execute the hash part as Javascript, as it's vulnerable to XSS without proper validating it. 强烈建议不要将散列部分作为Javascript执行,因为它容易受到XSS的攻击而无法正确验证。 You should watch the hash part, and on modification, do something. 您应该注意哈希部分,并在修改后执行一些操作。

An example; 一个例子; watch every 50 milliseconds for modifications in the hash part, and insert in a element with ID targetElement an heading with the hash part. 每隔50毫秒观察一次哈希部分的修改,然后将ID为targetElement的元素插入哈希部分的标题。 If the hash part is not valid, replace the current entry with home . 如果哈希部分无效,则用home替换当前条目。

var oldHash = '';
function watchHash(){
    // strip the first character (#) from location.hash
    var newHash = location.hash.substr(1);
    if (oldHash != newHash) {
        // assume that the parameter are alphanumeric characters or digits
        var validated = newHash.match(/^(\w+)$/);
        // make sure the hash is valid
        if (validated) {
            // usually, you would do a HTTP request and use the parameter
            var code = "<h1>" + validated[1] + "</h1>";
            var element = document.getElementById("targetElement");
            element.innerHTML = code;
        } else {
            // invalid hash, redirect to #home, without creating a new history entry
            location.replace("#home");
        }
        // and set the new state
        oldHash = newHash;
    }
}
// periodically (every 50 ms) watch for modification in the hash part
setInterval(watchHash, 50);

HTML code: HTML代码:

<a href="#home">Home</a>
<a href="#about">About Me</a>
<a href="#contact">Contact</a>
<div id="targetElement">
    <!-- HTML will be inserted here -->
</div>

The modern browsers are starting to support the event window.onhashchange 现代的浏览器已开始支持事件窗口。

In the meantime you can use the workaround proposed by Lekensteyn or maybe you can find something useful here: JavaScript/jQuery - onhashchange event workaround 同时,您可以使用Lekensteyn提出的解决方法,或者您可以在这里找到有用的方法: JavaScript / jQuery-onhashchange事件解决方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM