簡體   English   中英

在特定網址上顯示內容

[英]Show content on certain URL

我正在使用一個在線商店解決方案,該解決方案允許我建立一個簡單的在線商店。 除了html / css / javascript,我不能使用任何其他代碼。

我在模板中放入了一個簡單的圖像滑塊。 但我希望此滑塊僅顯示在首頁上。 現在,它顯示在每一頁上。

我可以使用這樣的javascript函數嗎:“如果url為“ www.example.com”,則顯示圖像滑塊,否則將其隱藏。”

像這樣的東西?

<script>
    $(function() {
    if(document.URL == "http://example.com/") {
...
...

</script>

預先感謝:)

我不知道您要嘗試執行此操作的確切情況或您為什么需要它的確切情況,但是

if (location.href == "http://example.com")

應該做。 Location.href返回頁面的URL,例如您的示例中的“ document.URL”。

如果您只是想獲取URL的某些部分,這是我在這里找到的一個非常酷的技巧。

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.hostname; // => "example.com"
parser.pathname; // => "/pathname/"

本質上,這是在JavaScript中創建一個link元素,該元素具有返回URL不同部分的屬性。 如果您的索引頁面可能有多個URL,這將是相關的。 例如,如果用戶當前位於http://example.com/index#something

(location.href == "http://example.com/")

將返回false。 但是,如果您在代碼中這樣做,

var parser = document.createElement('a');
parser.href = "http://example.com/index#something";

(parser.hostname+parser.pathname == "example.com/index")

最后一行對於http://example.com/indexhttp://example.com/index#something都將返回true。 利用您提供的有關該網站的信息,這是您的代碼應該是什么樣的最好的猜測。

var parser = document.createElement('a');
parser.href = location.href;

if (parser.hostname+parser.pathname != "example.com/index") //If user isn't on the index page
{
    $(".slidewrap").hide(); //Hide the div with the class slidewrap
}

window.location是正確的區域,它公開了一個hostname屬性,因此您可以只檢查站點名稱而不是整個URL,而只能檢查站點內本地路徑的路徑pathname 參見https://developer.mozilla.org/en-US/docs/Web/API/Location

因此,如果主頁為http://www.example.com/ ,則window.locaton.pathname === '/'

<script>
    $(function() {
        if (location.pathname == "/") {
            ...
        }
    });
</script>

我只是添加解決方案作為答案,因為我通過混合j4g和duncans代碼使其起作用:

<script>
$(function() {
if(location.pathname !== "/") {
$("#slidewrap").hide(); 
}
});
</script>

據我了解。 它說:如果位置不是索引,則隱藏#slidewrap:D,這很好用。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM