改变窗口位置,然后等待窗口加载? [英] Changing window location, then waiting for the window to load?

查看:86
本文介绍了改变窗口位置,然后等待窗口加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟我一起,我是一个完整的Javascript小白菜:P。所以,我想要做的是使用一个函数来加载一个网页。而且,在完成该功能后,我希望能够抓取页面上某个元素的HTML代码。这是我的代码到目前为止:

pre $ function change(){
window.location =www.aWebPage.com
window.onload = function(){
return document.ID_HERE.outerHTML;




$ b $ p
$ b无论什么原因,HTML代码的返回不会' t工作,但重定向。我是否正确地将该值返回给函数?有没有另一种方法可以使用多个函数,只有在窗口重定向后才能执行?

解决方案

这是因为一旦javascript读取window.location页面被刷新并且所有后续代码都不会被执行。为了解决这个问题,我们使用散列标签和查询字符串。例如,您可以将位置更改为www.awebpage.com#id。然后使用javascript检测查询字符串中的#id并执行您的代码。我在下面写了一个例子:

  function change(id){
window.location =www.aWebPage .com#id =+ id;
}

window.onload = function(){
var hash = window.location.hash;
if(hash.length> 0)
{
var id = hash.replace('#id =','');
返回document.id.outerHTML;
}
}


Bear with me, I'm a complete noob to Javascript :P. So, what I want to do is use a function to load a web page. And, after that function is done I want to be able to grab the HTML code of a certain element on a page. Here's my code so far:

function change(){
    window.location = "www.aWebPage.com"
    window.onload = function() {
     return document.ID_HERE.outerHTML;
    }   
}

For whatever reason the return of the HTML code doesn't work, but the redirect does. Am I return the value to the function properly? Is there another way where I could use multiple functions that only executed after the window has been redirected?

解决方案

This is because once javascript reads the window.location the page is refreshed and all subsequent code does not get executed. To get around this we use hash tags and query strings. You could for example change the location to be www.awebpage.com#id. Then use javascript to detect the "#id" in the querystring and execute your code. I have written up a sample below:

function change(id){
    window.location = "www.aWebPage.com#id=" + id;
}

window.onload = function() {
    var hash = window.location.hash;
    if (hash.length > 0)
    {
    var id = hash.replace('#id=','');
    return document.id.outerHTML;
    }  
} 

这篇关于改变窗口位置,然后等待窗口加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆