<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>
我的脚本无效。
试试这个
<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>
另一种方法是使用includes()
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中的任何位置作为参数。如果您的网址与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);