单击span时更改主题

change theme when clicking on span

本文关键字:span 单击      更新时间:2024-04-03

我需要一个函数来在点击报价时获取.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,这帮了我很大的忙。