Javascript jQuery:检查对象是否具有类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10657043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:23:42 来源:igfitidea点击:
jQuery: Check if an object has class
提问by colindunn
Trying to check if an object has a class. Seems simple enough, but I can't get it to work. Here is my code:
试图检查一个对象是否有一个类。看起来很简单,但我无法让它工作。这是我的代码:
Javascript
Javascript
$('ul.nav li').click(function(){
if $(this).hasClass('selected') {
alert('This is selected!');
}
else {
alert('This is not selected!');
}
});
$('ul.nav li:first-child').addClass('selected');
HTML
HTML
<ul class="nav">
<li>Who we work for</li>
<li>Articles and interviews</li>
<li>Job openings</li>
<li>What the #%!$@ is Post Typography?</li>
</ul>
<ul class="content">
<li>This is who we work for.</li>
<li>These are articles and interviews.</li>
<li>These are our job openings.</li>
<li>This is some info about Post Typography.</li>
</ul>
回答by YMMD
if $(this).hasClass('selected') {
should be
应该
if($(this).hasClass('selected')){
This would have been easily observed when you have had a look into the browser's error console. :-)
当您查看浏览器的错误控制台时,很容易观察到这一点。:-)
回答by Philemon philip Kunjumon
include the full code in
包括完整的代码
$(document).ready(function(){
$('ul.nav li').click(function(){
if ($(this).hasClass('selected')) {
alert('This is selected!');
}
else {
alert('This is not selected!');
}
});
$('ul.nav li:first-child').addClass('selected');
});
hope this helps..
希望这可以帮助..