Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.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 如何使用if语句使用jQuery更改祖辈元素的背景图像_Javascript_Jquery_Html_If Statement - Fatal编程技术网

Javascript 如何使用if语句使用jQuery更改祖辈元素的背景图像

Javascript 如何使用if语句使用jQuery更改祖辈元素的背景图像,javascript,jquery,html,if-statement,Javascript,Jquery,Html,If Statement,我试图做的是使用3个可单击的div作为开关,当单击时,它会更改元素的背景(使用属性数据图像src),该元素是div的祖辈 这是我的HTML: <header class="header-index locations-header col-lg-12 clearfix " data-parallax="scroll" data-image-src="images/2V1C8599.jpg"> <section class="locations-switcher col-

我试图做的是使用3个可单击的div作为开关,当单击时,它会更改元素的背景(使用属性数据图像src),该元素是div的祖辈

这是我的HTML:

<header class="header-index locations-header col-lg-12 clearfix " data-parallax="scroll" data-image-src="images/2V1C8599.jpg">
    <section class="locations-switcher col-md-12 clearfix">
        <div class="first-switch col-sm-4"><h2>div one</h2></div>
        <div class="second-switch col-sm-4"><h2>div two</h2></div>
        <div class="third-switch col-sm-4"><h2>div three</h2></div>
    </section>
</header>
任何关于它为什么不起作用的线索。我对javascript和jQuery还是相当陌生的。任何帮助都会非常好

use:
if($(this).hasClass('first-switch')){
instead of:
 if($("div", this).attr('class') === "first-switch") {
  • 我认为
    $('div',this)
    将查找子div,您需要查看已经找到的元素

  • 因为元素上还有其他类,
    .attr('class')
    将返回整个字符串,
    .hasClass()
    将检查整个列表

  • 在第一个源字符串中有一个额外的括号

  • 根据
    数据图像src
    的使用方式,您可能需要触发其他内容来重新绘制它。我通常手动设置
    .css('background-image','url('+srcString+'))


  • 对于初学者,请使用
    $().hasClass('second-switch')
    ,因为元素上还有其他类也可能必须更改
    data()
    not属性。。。。可能绑定到一个已经读取属性的插件如果这样做的话:像
    $(“.locations header”).data(“image src”,“./images/UBC Interior.jpg”)在使用data()和attr()时没有风险。。。它是一个正在读取属性的插件。我是否需要将插件集成到此函数中,以便它在单击时重新加载和读取新的数据图像src本身?
    
    use:
    if($(this).hasClass('first-switch')){
    instead of:
     if($("div", this).attr('class') === "first-switch") {