[英]change theme when clicking on span
我需要一个函数来在单击引号时获取.themechoice span的ID,并将其存储在变量“ theme”中,以便下面的函数将各节的主题更改为匹配的.themeChoice span id
q
$('.themeChoice').click(function() {
var theme = //need function here
$(this).parent().find('section').addClass(theme);
}); //end click a theme
头标记中的html
<style>
.light {
background-color: lightyellow;
border: double lightgreen small;
border-radius: 15px;
padding: 1em;
margin: 1em;
}
.dark {
background-color: black;
border: groove darkgray medium;
border-radius: 15px;
padding: 1em;
margin: 1em;
}
.neutral {
background-color: tan;
border: inset brown thick;
border-radius: 15px;
padding: 1em;
margin: 1em;
}
img {
width: 200px;
}
</style>
正文中的html
<section>
<p><h3>Pick a theme by clicking the quote you like most</h3></p>
<span="" id="light" class="themeChoice"><p>Future's so bright, you'll need sunshades.</p></span>
<span id="dark" class="themeChoice"><p>“Everyone is a moon, and has a dark side which he never shows to anybody.” -Mark Twain</p></span>
<span id="neutral" class="themeChoice"><p>“The hottest place in Hell is reserved for those who remain neutral in times of great moral conflict.” -Martin Luther King, Jr.</p></span>
</section>
您可以使用this.id
来获取被点击元素的ID,这就是这里的类名。
$('.themeChoice').click(function() {
var theme = this.id;
$(this).parent("section").addClass(theme);
});
同样,在您的情况下, .themeChoice
父元素是该部分。 您使用的选择器错误。
下面给出了一个稳定的代码,该代码删除了先前的主题类并添加了新的主题类,
$('.themeChoice').click(function() {
var theme = this.id;
var $parent = $(this).parent("section");
$parent.removeClass($parent.data("theme")).addClass(theme);
$parent.data("theme", theme);
});
jQuery().click()
函数接受回调,就像您添加的那样。 这回调函数被调用单击元素等等的范围内this
您单击处理程序的内部指的是点击的元素,所以你可以这样做:
$('.themeChoice').click(function() {
var theme = $(this).attr('id'); //Should return the id of clicked element a shortcut would be this.id like mentioned by another user
//Your class adding stuff
});
谢谢。 我最终使用了它,效果很好:
$('.themeChoice').click(function() {
var theme = this.id;
$('section').addClass(theme);
});
谢谢你们都提供了this.id,这对我们有很大帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.