2011-07-20 29 views
0

我是一名設計師,不是JS編碼器,所以任何幫助都會對此很好。使用javascript通過url字符串更改頁面上的內容

使用JavaScript或jQuery我將如何通過URL中的字符串替換頁面上的內容?

因此,如果內容「A」僅僅是通過這個http://www.example.com的正常內容,並且如果通過這個http://www.example.com/index.html?content=b'A'被內容'B'取代。

例如:

內容A

<div id="video-player"> 
vimeo code 
</div> 

要與內容B

<div id="video-player"> 
youtube code 
</div> 

經由串在像這樣http://www.example.com/index.html?player=youtube 鏈接替換,如果有在URL沒有字符串那麼它會默認並只顯示視頻代碼

編輯

確定這就是我的html頁面上立即

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 

<script type="text/javascript" src="js/test.js"></script> 
</head> 

<body> 

<div id="video-player"> 
vimeo 
</div> 

</body> 
</html> 

和JS網頁

window.location.href.split('?')[1].split('&')[0].split('content=')[1] 
var content_value = window.location.hash.substring(1) // For hashses OR 
var content_value = window.location.href.split('?')[1].split('&')[0].split('content=')[1] // For ? 
if (content_value === "b") { 
    $('#video-player').html(vimeo_code); 
} else { 
    $('#video-player').html(youtube_code); 

是這樣嗎?

+0

更精確。你想加載http://www.example.com/index.html?content=b頁面的某個地方?或者閱讀網址,看看你是否找到「content = b」,然後在某處顯示某個地方? – Cystack

+0

因此,如果網址中沒有字符串,我只是希望它顯示內容'A',但如果網址中有字符串like = b,那麼我希望'A'的內容替換爲'B'。 它將是一個div – Matu

回答

1

最簡單的方法是使用散列標籤。你可以使用?,但實施起來比較困難。所以,而不是index.html?content=b使用index.html#b,然後你可以通過使用window.location.hash.substring(1),這將給你的場景b引用。然後,您可以使用if語句來檢查該值並相應地調整內容。

另外,如果你需要使用?那麼你可以使用這個window.location.href.split('?')[1].split('content=')[1]但它不能保證在任何情況下工作,特別是如果你有一個以上的變量存在。對於多個變量,你可以使用

window.location.href.split('?')[1].split('&')[0].split('content=')[1] 

完整代碼現在這個樣子:

$(function() { 
    var youtube_code, vimeo_code, content_value; 
    youtube_code = "The code for Youtube goes here"; 
    vimeo_code = "The code for Vimeo goes here"; 
    content_value = (typeof window.location.href.split('player=')[1] !== "undefined") ? window.location.href.split('player=')[1] : ""; 

    if (content_value === "youtube") { 
    $('#video-player').html(youtube_code); 
    } else { 
    $('#video-player').html(vimeo_code); 
    } 
}); 

你也可以使用一些else if■如果你想要更多的內容選擇。根據您選擇的選項,使用前兩行中的一行。

編輯:將代碼更改爲完整的代碼(並優化了一下)。除了將youtube_codevimeo_code更改爲正確的值之外,您無需爲此添加其他任何內容。

編輯:優化並使其檢查居然有url中player=

+0

您使用的瀏覽器是?有沒有錯誤? – Fred

+0

哈哈,是的。我認爲這可能是這個。讓我想辦法解決這個問題並更改我的代碼... – Fred

+0

請參閱:http://jsfiddle.net/b4rsd/您需要包含jQuery! – Fred

0

我建議你使用ajax和xml。將xml文件放入您的保管箱文件夾,您可以隨時編輯該網址。

如果用戶選擇一個選項,ajax將更新該值而不刷新瀏覽器。

好東西是你可以在不登錄html編輯器/網站cms的情況下從你的手機更新網址,你也可以使用其他功能。