2010-03-19 62 views
0

我想点击一个#ID并打开一个URL - 但[作为新手] - 我似乎无法得到它。我使用点击ID并打开网址?

$('#Test').click(function() { 
    OpenUrl('some url'); 
    return false; 
}); 

回答

1

HM如果你的OpenURL函数看起来像这样的东西应该工作就好了:d

function OpenUrl(url){ 
    window.location = url; 
} 

BTW:为什么返回上点击假?

+0

他可能试图打开一个新窗口,在这种情况下,返回false是适当的,他应该使用'window.open' – 2010-03-19 17:45:14

2

只需使用window.location = 'some url'

$('#Test').click(function() { 
    window.location = 'http://www.google.com' 
    return false; 
}); 

要详细一点,window.location是不同的挺有意思的属性,你可以read more about it here的对象。总之,它包含以下属性(从链接的引用):

Property Description        Example 
hash   the part of the URL that follows the #test 
      # symbol, including the # symbol.  

host   the host name and port number.   [www.google.com]:80 

hostname  the host name (without the port number www.google.com 
      or square brackets). 

href   the entire URL.      http://[www.google.com]:80 
                /search?q=devmo#test 

pathname the path (relative to the host).  /search 

port   the port number of the URL.   80 

protocol  the protocol of the URL.    http: 

search the part of the URL that follows the ?q=devmo 
      ? symbol, including the ? symbol. 

由于window.location是一个对象,它也可以包含方法,其window.location一样。通过使用这些方法,您可以更好地控制页面的加载方式,即强制从服务器重新加载或允许浏览器使用缓存条目,跳过创建新的历史点等

这里是可用方法的概述:

Method   Description 
assign(url)   Load the document at the provided URL. 

reload(forceget) Reload the document from the current URL. forceget is a 
        boolean, which, when it is true, causes the page to always 
        be reloaded from the server. If it is false or not specified, 
        the browser may reload the page from its cache. 

replace(url)  Replace the current document with the one at the provided 
        URL. The difference from the assign() method is that after 
        using replace() the current page will not be saved in 
        session history, meaning the user won't be able to use 
        the Back button to navigate to it. 

toString()   Returns the string representation of the Location object's 
        URL. 

您也可以在新窗口中打开的资源,如果你想。请注意,有些用户不喜欢在新窗口中为他们打开链接,并且更愿意自己有意识地做出这一决定。但是,您可以做的是在您的点击处理程序中模拟某些功能,并尝试找出哪个鼠标按钮被点击。如果它是鼠标中键,那么大多数浏览器会在新窗口中打开链接。这不完全相同,因为用户将无法右键单击并选择“在新窗口中打开”,但它可能已经足够了。总之,这里是如何在新窗口中打开一个资源:

var WindowObjectReference; 

function openRequestedPopup() 
{ 
    WindowObjectReference = window.open(
        "http://www.domainname.ext/path/ImageFile.png", 
        "DescriptiveWindowName", 
        "resizable=yes,scrollbars=yes,status=yes"); 
} 

您可以read a lot more information here

+0

+1来查看细节。你可能想要包含一些关于'window.open'的东西 – 2010-03-19 17:46:30

3

喜欢的东西:

$("#Test").click(function(event){ 
     window.location.href = "some url"; 
     event.preventDefault(); 
});