Javascript Jquery更改CSS背景:检查div是否包含文本,然后执行操作
我正在尝试根据weatherType获取我的CSS背景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
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( );
}