在阅读了关于这个主题的一些问题/答案后,我试图让它对我有用,但我做不到。
故事情节是我有 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 is not a function
尽管 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 函数。
关于javascript - 如何使用 JavaScript 更改 HTML 元素的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42626773/