2010-03-19 61 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(); 
});