[英]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.