Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.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
Javascript Jquery更改CSS背景:检查div是否包含文本,然后执行操作_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript Jquery更改CSS背景:检查div是否包含文本,然后执行操作

Javascript Jquery更改CSS背景:检查div是否包含文本,然后执行操作,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试根据weatherType获取我的CSS背景 if($('#weatherType:contains("cloudy")')) { $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)'); } else if($('#weatherType:contains("clear sky")')) { $('body').css('bac

我正在尝试根据weatherType获取我的CSS背景

if($('#weatherType:contains("cloudy")')) {
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType:contains("clear sky")')) {
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')
};
HTML


展示当地天气
前端开发人员项目


在您的代码中,第一个if条件将始终为true,因为
$(…)
返回一个jQuery对象,该对象是一个truthy值,因此始终会执行第一个if块。改用


或者可以使用jQuery方法返回布尔值

if($('#weatherType').is(':contains("cloudy")')) {
//------------------^^^^-------
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType').is(':contains("clear sky")')) {
//-------------------------^^^^-------
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')
是一个选择器。要定义是否在文档中找到它,必须使用返回元素数的值(本例为1)

然后:


length
将为您提供一个
int
来检查div中的文本。
var n=$(“div”).length还值得注意的是.contains()是区分大小写的!我非常感谢你的帮助@埃里克·萨尔迪瓦:很乐意帮忙:)
if($('#weatherType:contains("cloudy")').length) {
//--------------------------------------^^^^^^-------
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType:contains("clear sky")').length) {
//------------------------------------------------^^^^^^-------
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')
if($('#weatherType').is(':contains("cloudy")')) {
//------------------^^^^-------
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType').is(':contains("clear sky")')) {
//-------------------------^^^^-------
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')
if ($('#weatherType:contains("cloudy")').length >0) {
    $('body').css(  );
} else if ($('#weatherType:contains("sunny")').length >0) {
    $('body').css(  );
}