单击span时更改主题
change theme when clicking on span
我需要一个函数来在点击报价时获取.themechoice span的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>
您可以使用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);
});
谢谢你们两个。id,这帮了我很大的忙。
相关文章:
- 兰吉 |如何在 span 标签上使用单击事件删除突出显示的文本
- jQuery复选框和span共享一个单击事件
- jquery单击链接并获取单选输入值以更改span中的文本
- 单击span时更改主题
- 如何在单击按钮时显示文本(按钮被<span></span>标记包围)
- 单击时切换DIV和SPAN文本
- 如何使用 JQuery 检索具有特定类的 span 元素中的文本,该元素位于单击的对象内
- 使用 jQuery 单击输入单选按钮时更改 span 的文本值
- 更改单击的链接 SPAN 标记上的颜色
- 通过jQuery将DISPLAY:NONE添加到span,当:鼠标单击span外部,或单击EXIT按钮,等等+
- 如何从 span 标记上的单击事件中获取选定的列表项值
- 将占位符值替换为单击的 span 标记的内部 HTML
- 当我单击元素数学/物理/化学时,如何使用jQuery获取SPAN ID
- 如何在span上获取表td值,然后单击删除该行
- <的缺少单击事件;span>内部<按钮>元素
- 单击span时获取附近的输入元素(onclick事件)
- 表单元格内span或td的单击事件处理程序不起作用
- 如何在单击span时获取数据
- 选择<span>on单击
- 单击selenium中存在的span元素