我编写了一个非常简单的函数来检查标记类名。我使用.attr()将它附加到div(s)上,似乎没有问题。
但是,$(this).attr('class')不能显示正确的类名并只显示
“未定义”
。实际上,我想用$(this)做更多的事情,所以我在一开始就停下来是很糟糕的。
有人能告诉我为什么会发生这种事吗?
<div class="testing class1" >Something here</div>
<div class="testing class2" >Something here</div>
<script>
$("div.testing").attr('onclick', 'checkClass()');
function checkClass(){
alert( $(this).attr('class'));
// what do something more with "$(this)"
}发布于 2017-11-26 16:54:32
您必须将它传递给函数,因为$(this) = window;
请试试这个:
$("div.testing").attr('onclick', 'checkClass(this)');
function checkClass(e){
alert( e.className);
// what do something more with e, this is you clicked element
}发布于 2017-11-26 16:27:59
尝试以以下方式实现它,您的代码将输出undefined内部警报,因为this引用了checkClass()函数,而不是您试图瞄准的元素,请参见下面的演示,您应该了解如何制作一个简单的插件
$.fn.checkClass = function() {
$(this).on('click', function() {
console.log($(this).attr('class'));
});
}
$("div.testing").checkClass();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing class1">Something here</div>
<div class="testing class2">Something here</div>
发布于 2017-11-26 16:33:49
虽然jQuery有自己的方法从元素中添加/移除类,但对于枚举没有任何方法。因此,您应该使用本机js方法。
var checkClass = e => {
alert(e.target.classList)
}
$("div.testing").click(checkClass)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing class1" >Something here</div>
<div class="testing class2" >Something here</div>
https://stackoverflow.com/questions/47498242
复制相似问题