单击时将类添加到div [英] Add class to div when clicked
问题描述
我试图单击时将一个类添加到div元素中.我无法使其正常工作,我将其设置与此类似:
I am trying to get a class to be added to a div element when clicked. I can not get it to work, I have it set up similar to this:
javascript:
javascript:
function choose() {
this.addClass("selected");
}
html:
<div class="initialclass" onclick="choose()">CLICK</div>
该功能中还有其他javascript命令可以正常运行,只是无法添加该类.
I have other javascript commands in that function that are working properly I just can't get the class to add.
推荐答案
当前代码有两个问题.首先是JS函数中的this
引用了window
,而不是单击的元素.其次,如果它确实引用了该元素,则它将是DOMElement而不是jQuery对象,因此它将没有addClass()
方法-您需要将其转换为jQuery对象.试试这个:
You have two issues with your current code. First is that this
in your JS function refers to the window
, not the element that was clicked. Second if it did refer to that element, it would be a DOMElement, not a jQuery object, so it would not have the addClass()
method - you need to convert it to a jQuery object. Try this:
<div class="initialclass" onclick="choose(this)">CLICK</div>
function choose(el) {
$(el).addClass("selected");
}
但是请注意,使用JavaScript连接事件是一种更好的做法.在使用jQuery时,您可以执行以下操作:
Note however, that it is better practice to hook up your events using JavaScript. As you are using jQuery, you can do this:
<div class="initialclass">CLICK</div>
$(function() {
$('.initialclass').click(function() {
$(this).addClass("selected");
});
});
这篇关于单击时将类添加到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!