簡體   English   中英

如何根據頁面URL有條件地顯示HTML

[英]How to conditionally display HTML based on the page URL

我有幾個不同的網頁 -

www.foo.com/index.html
www.foo.com/dog.html
www.foo.com/cat.html

假設頁面非常相似,除了圖像和頁面中間的一些文本,該頁面是該頁面獨有的。

我有一個外部腳本,使用模板為每個頁面動態創建HTML,並替換各種變量和配置。 我試圖弄清楚如何只為某個頁面顯示某段HTML(例如cat.html)

在偽代碼中,這就是我想要做的 -

  <style>
    function isCatPage() {
      if page.url.contains("cat.html")
        return true;
      else
        return false;
      end
    }
  </style>

  if isCatPage {
  <bold>This text only appears on cat.html</bold>
  }

  <p> This is random dynamically generated HTML</p>
</body>

使用基本的javascript在特定的HTML頁面上顯示<bold>

謝謝!

我會使用jquery並執行以下操作:

<script type='text/javascript'>
    // only run this when the page finishes loading
    $(document).ready(function () {
        // if cat.html exists in the url
        if (window.location.href.indexOf('cat.html') > -1) {
            // select the p by its id and hide it or - 
            $('#conditional').css('visibility', 'visible');
        }
        else {
            // show it
            $('#conditional').css('visibility', 'hidden');
        }
    });
</script>

<p id='conditional'>This text only appears on cat.html</p>
<p>This is random dynamically generated HTML</p>

獲取當前網址,並將其拆分

var url_parts = location.href.split(/\//g);
var page = url_parts[url_parts.length-1];

page應包含當前頁面(例如cat.html

雖然,我真的建議你使用服務器來做這種事情

暫無
暫無

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

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