[英]How to change the CSS of an HTML element with JavaScript
阅读有关此主题的一些问题/答案后,我尝试使其对我有用,但我不能。
故事情节是我有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">
),但是我<li class="liMachine switch">
此错误:
event.toElement.closest(...)。css不是函数
尽管有event.toElement.closest
返回正确的元素:
那么我在做什么错呢?
$('.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函数。
由于您正在使用Meteor,因此您可能更喜欢以下语法:
"click .switch": function(event){
$(event.target).css("background-color", "black");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.