繁体   English   中英

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

[英]Jquery to change CSS background: Checking to see if div contains text, then action

我试图根据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

<body>
<div class="text-center">
<h1> Show the Local Weather</h1>
<h3>Front End Developer Project</h3>
<ul class="list-unstyled">
  <i class="fa fa-home" aria-hidden="true"></i>
  <li class="btn btn-default" id="city"></li>

  <i class="wi wi-day-cloudy"></i>
  <li class="btn btn-default" id="weatherType"></li>
</br>
  <i class="wi wi-thermometer"></i>
  <li class="btn btn-default" id="fTemp"></li>

  <i class="wi wi-strong-wind"></i>
  <li class="btn btn-default" id="windSpeed"></li>
</ul>

在你的代码中,第一个if条件总是为真,因为$(...)返回一个jQuery对象,这是一个真值,所以总是第一个if块被执行。 请改用length属性

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)')

或者你可以使用jQuery is()方法返回一个布尔值。

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)')

:contains是一个选择器。 要定义它在文档中找到的IF,你必须使用.length返回元素的数量(这种情况:1)。

然后:

if ($('#weatherType:contains("cloudy")').length >0) {
    $('body').css(  );
} else if ($('#weatherType:contains("sunny")').length >0) {
    $('body').css(  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM