Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.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包含其中一个字符串,则在头部添加css_Jquery_Css - Fatal编程技术网

Jquery 如果url包含其中一个字符串,则在头部添加css

Jquery 如果url包含其中一个字符串,则在头部添加css,jquery,css,Jquery,Css,我正在尝试编写一个脚本,如果html文档的url包含四个可能字符串中的一个,它将向html文档添加样式表 但是,该代码仅适用于包含string1且不包含任何其他字符串的URL $(document).ready(function() { if (window.location.href.indexOf("string1"||"string2"||"string3"||"string4") > -1) { if (document.createStyleSheet) {

我正在尝试编写一个脚本,如果html文档的url包含四个可能字符串中的一个,它将向html文档添加样式表

但是,该代码仅适用于包含
string1
且不包含任何其他字符串的URL

$(document).ready(function() {
  if (window.location.href.indexOf("string1"||"string2"||"string3"||"string4") > -1) {
    if (document.createStyleSheet) {
      document.createStyleSheet('path/to/css.css');
    }
    else {
      $("head").append($("<link rel='stylesheet' href='path/to/css.css'/>"));
    }
  }
});
$(文档).ready(函数(){
if(window.location.href.indexOf(“string1”| |“string2”| |“string3”| |“string4”)>-1){
if(document.createStyleSheet){
document.createStyleSheet('path/to/css.css');
}
否则{
$(“head”)。追加($(“”);
}
}
});

我做错了什么?

最好使用正则表达式:

 if (window.location.href.match(/(string1|string2|string3|string4)/) != null) {
当你写作时

window.location.href.indexOf("string1"||"string2"||"string3"||"string4")
它首先评估论点

"string1"||"string2"||"string3"||"string4"
并将结果传递给
indexOf()
。当您计算
|
运算符序列时,它将返回序列中的第一个真值,因此您的代码相当于

window.location.href.indexOf("string1")
如果要与多个字符串进行比较,需要对每个字符串组合调用
indexOf()
的结果,不能在参数中使用
|

if (window.location.href.indexOf("string1") > -1 || window.location.href.indexOf("string2") > -1 || window.location.href.indexOf("string3") > -1 || window.location.href.indexOf("string4") > -1)
但更简单的方法是使用正则表达式

if (window.location.href.match(/string1|string2|string3|string4/)
您认为
“string1”| |“string2”| |“string3”| |“string4”
的计算结果是什么?