[英]How to change the CSS of an HTML element with JavaScript
After reading some questions/answers about this subject I have tried to make it works for me but I can't. 阅读有关此主题的一些问题/答案后,我尝试使其对我有用,但我不能。
The story line is that I have X elements (so it means no ID just class) and I want to change the background when I click in one. 故事情节是我有X个元素(所以这意味着没有ID只是一个类),并且我想在单击一个元素时更改背景。
So with JS I did: 因此,使用JS,我做到了:
'click .switch' (event) {
event.toElement.closest("li").css('background-color','black');
if(this.stateMachine == 'running'){
Meteor.call("switch", this.nameMachine);
}
},
to get the container (here a <li class="liMachine switch">
) but I have this error: 获取容器(这里是
<li class="liMachine switch">
),但是我<li class="liMachine switch">
此错误:
event.toElement.closest(...).css is not a function
event.toElement.closest(...)。css不是函数
Despite the event.toElement.closest
returns the right element: 尽管有
event.toElement.closest
返回正确的元素:
So what am I doing wrong ? 那么我在做什么错呢?
$('.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>
If $(event.target)
works for you then the problem was of course that you did not pass a jQuery object. 如果
$(event.target)
为您工作,那么问题当然是您没有传递jQuery对象。 So you can not use jQuery functions on non jQuery object. 因此,您不能在非jQuery对象上使用jQuery函数。
Since you are using Meteor, you may prefer this syntax: 由于您正在使用Meteor,因此您可能更喜欢以下语法:
"click .switch": function(event){
$(event.target).css("background-color", "black");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.