【问题标题】:How to change the CSS of an HTML element with JavaScript如何使用 JavaScript 更改 HTML 元素的 CSS
【发布时间】:2017-03-06 21:41:09
【问题描述】:

在阅读了一些关于这个主题的问题/答案后,我试图让它对我有用,但我做不到。

故事情节是我有X元素(所以这意味着没有ID只是类),我想在点击一个时更改背景。

所以我用 JS 做了:

'click .switch' (event) {
    event.toElement.closest("li").css('background-color','black');


    if(this.stateMachine == 'running'){
      Meteor.call("switch", this.nameMachine);
    }

  },

获取容器(这里是<li class="liMachine switch">)但我有这个错误:

event.toElement.closest(...).css 不是函数

尽管event.toElement.closest 返回正确的元素:

那么我做错了什么?

【问题讨论】:

  • event.toElement 更改为$(this)$(event.target)。最好是前者
  • @RoryMcCrossan 没有任何反应,没有错误但没有变化
  • 你的选择器中click 是什么元素?这不是有效的 HTML,除非你使用了一些你没有提到的奇怪的库
  • 使用 MeteorJS @RoryMcCrossan
  • 它适用于$(event.target) !!

标签: javascript jquery html css meteor


【解决方案1】:

$('.liContainer.switch').on('click', function() {
    $(this).toggleClass('active');
});
.active {
  background-color: powderblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liContainer switch">one</li>
  <li class="liContainer switch">two</li>
  <li class="liContainer switch">three</li>
</ul>

如果$(event.target) 适合您,那么问题当然是您没有传递 jQuery 对象。所以你不能在非 jQuery 对象上使用 jQuery 函数。

【讨论】:

  • 在 sn-p 中它可以工作,但在我的 JS 中没有任何反应(我放了一些日志但没有显示)
【解决方案2】:

由于您使用的是 Meteor,因此您可能更喜欢以下语法:

"click .switch": function(event){
$(event.target).css("background-color", "black");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2015-08-16
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2010-09-12
    • 2016-06-17
    相关资源
    最近更新 更多