我正在尝试编写一个脚本,如果它的url包含四个可能的字符串之一,则会在html文档中添加样式表
但是,该代码仅适用于包含string1
且不包含其他字符串的网址。
$(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'/>"));
}
}
});
我做错了什么?
答案 0 :(得分:0)
最好使用正则表达式:
if (window.location.href.match(/(string1|string2|string3|string4)/) != null) {
答案 1 :(得分:0)
写作时
window.location.href.indexOf("string1"||"string2"||"string3"||"string4")
首先评估参数
"string1"||"string2"||"string3"||"string4"
并将结果传递给indexOf()
。当您评估一系列||
运算符时,它会返回序列中的第一个truthy值,因此您的代码等效于
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/)