如何根据页面URL有条件地显示HTML

时间:2014-06-06 08:41:45

标签: javascript html

我有几个不同的网页 -

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

假设页面非常相似,除了图像和页面中间的一些文本是该页面独有的。

我有一个外部脚本,它使用模板为每个页面动态创建HTML,并替换为各种变量和配置。我正在试图找出如何仅针对特定页面显示某段HTML(例如cat.html)

在psuedo-code中,这就是我想做的事情 -

  <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>

谢谢!

2 个答案:

答案 0 :(得分:3)

我会使用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>

答案 1 :(得分:0)

获取当前网址并将其拆分

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

page应包含当前页面(例如cat.html

虽然,我真的建议你使用服务器来做这种事情

相关问题