Jquery 在if语句中从数组中请求多个值
我想根据URL中的几个字符串更改-元素的背景图像。我可以改变每一个词的背景,比如“Site1”,但我想有不止一个词。所以我试了一下:Jquery 在if语句中从数组中请求多个值,jquery,css,arrays,if-statement,Jquery,Css,Arrays,If Statement,我想根据URL中的几个字符串更改-元素的背景图像。我可以改变每一个词的背景,比如“Site1”,但我想有不止一个词。所以我试了一下: var urlstring = new Array( "Site1", "Site2", "Site3" ); //When one of these words are in the URL, then change the background. var imageUrl ="Path to image"; if(window.location.href.
var urlstring = new Array( "Site1", "Site2", "Site3" ); //When one of these words are in the URL, then change the background.
var imageUrl ="Path to image";
if(window.location.href.indexOf(urlstring) > -1) {
$('#myelement').css('background-image', 'url(' + imageUrl + ')');
}
我相信有专家会对此发笑,但完成这项工作会非常有帮助(还有更多类似的相关任务…迭代数组的每个元素,检查它是否在URL中:
urlstring.forEach(function(keyword) {
if (window.location.href.indexOf(keyword) > -1) {
// ...
}
});
很抱歉反应太晚,但是…这很有效!非常感谢。