简体   繁体   English

网址中存在特定字符串时隐藏元素

[英]Hide an element when a specific string is present in the url

I want to hide a button when the string "wholesale' is present in the url. I've tried a few variations of the following code but it just won't work. 当URL中出现字符串“ wholesale”时,我想隐藏一个按钮。我尝试了以下代码的一些变体,但它根本无法工作。

<script type="text/javascript">
$(document).ready(function () {
    if (/wholesale/.test(window.location.href)) {
       document.getElementsByClassName('variations_button')[0].style.display = 'none';
    }
});
</script>

May be this will help. 可能会有所帮助。

 var patt = new RegExp("wholesale");
    if (patt.test(window.location.href)) {
          $('.variations_button').hide();
        }

you are doing wrong with the select element by class name code 您通过类​​名代码对select元素做错了

it should be like this: 应该是这样的:

document.getElementsByClassName('variations_button')[0].style.display='none'

Note: 注意:

document.getElementsByClassName returns an array of elements with the same class name. document.getElementsByClassName返回具有相同类名的元素数组。 So document.getElementsByClassName('variations_button')[0] will return the first element with the class name variations_button . 因此document.getElementsByClassName('variations_button')[0]将返回类名称为variations_button的第一个元素。

you have a problem with getElementByClassName , it should be getElementsByClassName and will return a HTMLCollection (Array like object) not an element. 您在getElementByClassName遇到问题,应该是getElementsByClassName并且将返回HTMLCollection (类似于对象的数组)而不是元素。 You should probably also use jQuery if that is already loaded on the page. 如果页面上已经加载了jQuery,则可能还应该使用jQuery。 jQuery is an array like object of HTMLElements that will give you methods that will run over the entire collection. jQuery是类似于HTMLElements对象的数组,它将为您提供将在整个集合中运行的方法。

edit: here is a working example, click 'Run code snippet' to see the result. 编辑:这是一个有效的示例,单击“运行代码段”以查看结果。 I had to change the regex to match what was in the snippet, but you should get the idea. 我必须更改正则表达式以匹配摘要中的内容,但是您应该明白这一点。

 console.log( 'is jQuery installed on the page', typeof $ !== void 0 ); $(function () { console.log( 'href', window.location.href ); if (/stacksnippets/.test(window.location.href)) { console.log('regex found in href'); $('.variations_button').css('background', '#3cf'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> <button class="variations_button">variations button</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM