如何在URL包含特定字符串时禁用元素?

问题描述 投票:0回答:5

 <div class="test-class">
    <div class="test-class1" id="test-id1">hello 1</div>
     <div class="test-class2" id="test-id2">hello 2</div>             
    <div class="test-class3" id="test-id3">hello 3</div>
  </div>

当页面URL包含字符串?fullpost时,我想禁用/隐藏Second [div](id =“test-id2”)。

例如:如果我的网址是http://www.example.com/post_1.html?fullpost,那么test-id2 div不应该是活动的。

如果URL仅为http://www.example.com/post_1.html,那么test-id2 div应该是活动的。

<script>
let element = document.getElementById("test-id2");

if(window.location.href.search("?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>

我的脚本无效。

javascript html css blogger blogspot
5个回答
0
投票

试试这个

<script>
  let element = document.getElementById("test-id2");

  if(window.location.href.includes("?fullpost")){
     element.parentNode.removeChild(element);
  }
</script>

0
投票

看起来当我运行它时,window.location.href.search(“?fullpost”)自然会被解析为正则表达式。所以你需要逃避'?'

<script>
let element = document.getElementById("test-id2");

if(window.location.href.search("/?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>

另一种方法是使用includes()

if(window.location.href.includes("?fullpost"))
{

0
投票

我使用正则表达式修复它,检查下一个代码

var element = document.getElementById("test-id2");
var reg = /(\?|\&)?fullpost/g;
var url = window.location.href;
if (reg.exec(url) !== null) {
    element.parentNode.removeChild(element);
}

这是快照https://output.jsbin.com/cataxix?fullpost的完整页面

正则表达式将检查URL是否包含fullpost作为第一个参数或URL中的任何位置作为参数。如果您的网址与http://www.example.com/post_1.html?anything&fullpost相同,则可以使用。


0
投票

你应该使用indexOf()而不是search()

let element = document.getElementById("test-id2");
var url = window.location.href;
if(url.indexOf("?fullpost") > -1) 
{ 
  element.parentNode.removeChild(element);
}

0
投票

在该元素上添加一个监听器 - 您希望它仅防止特定页面

let ELM = document.getElementById("test-id2");
ELM.addEventListener("click",(ev) => {
   if(window.location.href.test(/\?fulpost/)){
     //ev.preventDefault(); // for <a></a>
     ev.stopImmediatePropagation(); // this will prevent any click_event from execution
   }
},true);
© www.soinside.com 2019 - 2024. All rights reserved.