javascript - 单击跨度时更改主题

标签 javascript jquery html css

我需要一个函数来在单击引号时获取 .themechoice 跨度的 ID,并将其存储在变量“主题”中,以便下面的函数将部分的主题更改为匹配的 .themeChoice 跨度 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 的父元素是该部分。您使用的选择器是错误的。

DEMO

下面给出了删除以前的主题类并添加较新的主题类的稳定代码,

$('.themeChoice').click(function() {
  var theme = this.id;
  var $parent = $(this).parent("section");
  $parent.removeClass($parent.data("theme")).addClass(theme);
  $parent.data("theme", theme);
});

DEMO

关于javascript - 单击跨度时更改主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534663/

相关文章:

javascript - 团体与 self 的街机物理碰撞回调

javascript - Angular ngHint - 表达式不支持连字符

html - 使两个 div 位于同一条边距线上,即使浏览器的大小发生变化也保持在那里

html - 更改网页中的 POST 值?谜语帮助?

javascript - "Resource interpreted as script but transferred with MIME type text/html."

javascript - 页脚仅在调整大小后可见

javascript - DOM click() 不适用于此按钮

javascript - 在多个事件上运行函数

jquery - 阻止 href 打开链接,但仍执行其他绑定(bind)事件

javascript - 隐藏farbtastic颜色代码