javascript 根据url显示div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19886883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:09:24  来源:igfitidea点击:

Show div based on url

javascripthtml

提问by Sebbo

I've been trying to find a short and easy to understand javascript that show a div based on the URL but all scripts I find doesn't seem to work.

我一直在寻找一个简短易懂的 javascript,它根据 URL 显示一个 div,但我找到的所有脚本似乎都不起作用。

I have this div on my page and the css file hides the div with: display:none;

我的页面上有这个 div,css 文件隐藏了 div: display:none;

<div id="idofthedivtohide"><span>Success!</span></div>

When I go to url: contact.php?success I want the div to change to display: block;

当我转到 url: contact.php?success 我希望 div 更改为 display: block;

Can someone help me with this? Many examples make it work with like 4 lines of code.

有人可以帮我弄这个吗?许多示例使它可以使用 4 行代码。

I've tried this code but it doesn't seem to work:

我试过这段代码,但它似乎不起作用:

<script type="text/javascript">
if (window.location.search.search(success)) document.getElementById("idofthedivtohide").style.display = "block"
</script>

回答by José SAYAGO

Here is another solution, more "human friendly":

这是另一个解决方案,更“人性化”:

HTML

HTML

<div id="idofthedivtohide">
  <span>Success!</span>
</div>

JavaScript

JavaScript

<script type="text/javascript">
  // Get URL
  var url = window.location.href;
  // Get DIV
  var msg = document.getElementById('idofthedivtohide');
  // Check if URL contains the keyword
  if( url.search( 'success' ) > 0 ) {
      // Display the message
      msg.style.display = "block";
  }
</script>

回答by Roko C. Buljan

<div id="success"><span>Success!</span></div>

var locSearch = window.location.search.substring(1).split('&')[0];
if(locSearch){
    document.getElementById( locSearch ).style.display = "block";
}

The above will handle

以上将处理

http://example.exm/page.html?success  // success

same as

与...一样

http://example.exm/page.html?success&user=2971024&votes=0 // success