Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如果URL包含X,则尝试向元素添加类_Jquery_Css - Fatal编程技术网

Jquery 如果URL包含X,则尝试向元素添加类

Jquery 如果URL包含X,则尝试向元素添加类,jquery,css,Jquery,Css,试着开始使用这段代码 <script type="text/javascript"> $(function (){ if ( document.location.href.indexOf('product') > -1){ $('.featproducts').addClass("display-none") } }); </script> $(函数(){ if(document.location.href.indexOf('product')>

试着开始使用这段代码

<script type="text/javascript">
$(function (){
    if ( document.location.href.indexOf('product') > -1){
    $('.featproducts').addClass("display-none")
}
});
</script>

$(函数(){
if(document.location.href.indexOf('product')>-1){
$('.featproducts').addClass(“显示无”)
}
});
网址是:

这是一些测试小提琴

恐怕是俄语的,这会让你的理解更加复杂

知道它为什么不起作用吗?谢谢

我想分配一个类
。如果类
“featproducts”
的任何元素在URL中显示为
“product”
,则将其显示为无

更新

提琴 使用
#
我能够向元素添加一个类

然而,在生产现场,我无法使用
#
.featproducts

所以失败的不是代码。

谢谢你的提醒。


您需要在jQuery中使用
来定位类,因此您可以执行以下操作:

$('.featproducts').addClass("display-none");

天哪!我怎么能看不到它

演示: 忽略警报,点击“运行”

它必须是:

window.location.href


if ( window.location.href.indexOf('product') > -1){
    $('.featproducts').addClass("display-none")
}

选择器错误。我们可以在您的问题中看到已编辑的代码吗?你也可以粘贴网页URL或类似的东西吗?我几乎可以肯定问题出在你的IF条件上。@LShetty我刚刚编辑了这个问题。在前面的
'featproducts'
选择器中添加了一个点,因此现在是
'.featproducts'
。没有什么变化。URL是其中XXXX是产品的ID。对,现在发布相关的HTMLand,如果您在if条件之前发出警报($('.featproducts').length),您会得到什么?编辑后的代码仍然不起作用。控制台中未显示任何错误。
.display none{display:none;
}@tusargupta控制台打印“null”。@tusargupta但有。至少源代码是这样说的。那么为什么控制台日志会显示null呢?根据W3C,它们是一样的。实际上,为了跨浏览器安全,您应该使用window.location而不是document.location。请参见:
window.location.href


if ( window.location.href.indexOf('product') > -1){
    $('.featproducts').addClass("display-none")
}