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



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

我想禁用/隐藏第二个 [div] (id="test-id2"( ,当页面 URL 包含字符串 ?fullpost 时。

例如:如果我的URLhttp://www.example.com/post_1.html?fullpost那么test-id2 div不应该处于活动状态。

例如,如果URL仅http://www.example.com/post_1.htmltest-id2 div应该处于活动状态。

<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>

我的脚本不起作用。

试试这个

<script>
let element = document.getElementById("test-id2");
if(window.location.href.includes("?fullpost")){
element.parentNode.removeChild(element);
}
</script>

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

<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("/?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>

另一种方法是使用 include((

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

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

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 中的任何位置作为参数。 如果您的URL是这样的 http://www.example.com/post_1.html?anything&fullpost 它将起作用。

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

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

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

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

最新更新