我需要一个函数来获取点击引号时的.themechoice范围的id,并将其存储在变量' theme'以便下面的函数将各部分的主题更改为匹配.themeChoice span id
JQ
$('.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>
答案 0 :(得分:2)
您可以使用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);
});
答案 1 :(得分:0)
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
});