Javascript 如何使用if语句使用jQuery更改祖辈元素的背景图像
我试图做的是使用3个可单击的div作为开关,当单击时,它会更改元素的背景(使用属性数据图像src),该元素是div的祖辈 这是我的HTML: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-
<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") {