我想通过特定类名选择一个元素(该元素包含多个类)。我引用了 this answer但对我不起作用。
<i class="fas fa-star fa-lg clicked"></i>
<i class="fas fa-star fa-lg"></i>
<i class="fas fa-star fa-lg"></i>
clicked
是一个自定义类,里面有 color:red
。
Javascript 代码:
$("i").click(()=> {
changeColor();
})
const changeColor = () => {
if (!$(this).hasClass('clicked')) {
console.log('not clicked class')
}
}
或
const changeColor = () => {
if ($("i:not(.clicked)")){
console.log("no clicked class")
}
}
这两种实现都不起作用。如果你知道为什么,请告诉我。
最佳答案
您没有正确捕获 this
引用,箭头符号不能使用隐式 this
引用,避免将它与 jQuery
一起使用:
An arrow function expression has a shorter syntax than a function expression and does not have its own
this
,arguments
,super
, ornew.target
. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
我已经修改了你的代码,所以它可以像你期望的那样工作:
$("i").click(function()
{
changeColor($(this));
});
const changeColor = (obj) =>
{
if (!obj.hasClass('clicked'))
console.log('not clicked class');
}
.as-console {background-color:black !important; color:lime;}
.clicked {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="fas fa-star fa-lg clicked">Button 1</i>
<i class="fas fa-star fa-lg">Button 2</i>
<i class="fas fa-star fa-lg">Button 3</i>
关于javascript - jQuery 中的“没有类”选择器。通过包含多个类的特定类名选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203234/