Jquery 如何确定是否应用了类?
我想检查一个“特定”类是否应用于div中的跨度Jquery 如何确定是否应用了类?,jquery,Jquery,我想检查一个“特定”类是否应用于div中的跨度 $('#div').click(function() { console.log($(this).find('.myImgClass').length); // returns 0-if not found // 1 if found } HTMl 这是正确的方法吗?使用以下方法: var hasMyImgClassClas
$('#div').click(function() {
console.log($(this).find('.myImgClass').length); // returns 0-if not found
// 1 if found
}
HTMl
这是正确的方法吗?使用以下方法:
var hasMyImgClassClass = $("span").hasClass("myImgClass");
请使用以下方法执行此操作:
var hasMyImgClassClass = $("span").hasClass("myImgClass");
看起来是正确的(除了div选择器之外),但如果要专门检查跨距,请将其更改为:
$('div').click(function() {
console.log($(this).find('span.myImgClass').length);
});
看起来是正确的(除了div选择器之外),但如果要专门检查跨距,请将其更改为:
$('div').click(function() {
console.log($(this).find('span.myImgClass').length);
});
您的选择器错误,
div
而不是#div
$('div').click(function() {
console.log($(this).has('.myImgClass').length);
});
您的选择器错误,
div
而不是#div
$('div').click(function() {
console.log($(this).has('.myImgClass').length);
});
这应该能奏效
$('div').click(function() {
alert("Spans with .myImgClass: " + $(this).children('span.myImgClass').length);
});
如果类只需要div,则:
$('div > span.myImgClass').click(function() {
var theSpan = $(this);
var theDiv = theSpan.parent();
alert("Div with Span with .myImgClass.");
});
这应该能奏效
$('div').click(function() {
alert("Spans with .myImgClass: " + $(this).children('span.myImgClass').length);
});
如果类只需要div,则:
$('div > span.myImgClass').click(function() {
var theSpan = $(this);
var theDiv = theSpan.parent();
alert("Div with Span with .myImgClass.");
});
但这并不能告诉您元素是否有该类的后代。我认为他的意思是
$(“div>span”)
@Erik:即使如此,在这个单击事件处理程序的上下文中,.hasClass()
也不是特别有用。您必须首先获得对span
的引用才能使用它,例如$(this)。查找('span')
,然后为什么不直接在选择器中使用类名?我的答案只是引用了这个答案(需要更多的工作),而不是问题。@Erik Philips:我不得不误解了OP的意图。;)但这并不能告诉您元素是否有该类的后代。我认为他的意思是$(“div>span”)
@Erik:即使如此,在这个单击事件处理程序的上下文中,.hasClass()
也不是特别有用。您必须首先获得对span
的引用才能使用它,例如$(this)。查找('span')
,然后为什么不直接在选择器中使用类名?我的答案只是引用了这个答案(需要更多的工作),而不是问题。@Erik Philips:我不得不误解了OP的意图。;)是的,那很好。。。无论如何,没有对错之分。根据具体操作,例如,如果要过滤div
s,也可以使用.has
:是的,这很好。。。无论如何,没有对错之分。根据具体操作,例如,如果要过滤div
s,也可以使用.has
:注意.has
返回jQuery对象。注意.has
返回jQuery对象。这会更改单击事件处理程序绑定到的元素。。。你为什么这么做?OP似乎希望click处理程序绑定到div。这将更改click事件处理程序绑定到的元素。。。你为什么这么做?OP似乎希望click处理程序绑定到div。我认为div>span.myImgClass:
应该是div>span.myImgClass,对吗?但是$('div>span.myImgClass')
将选择span
元素,而不是div
s,因此单击事件处理程序绑定到span元素。我认为div>span.myImgClass:
应该是div>span.myImgClass
,对吗?但是$('div>span.myImgClass')
将选择span
元素,而不是div
s,因此单击事件处理程序绑定到span元素。