Swe*_*ely 0 jquery if-statement
显示一张图片,然后点击一个按钮.如果按钮类匹配图片的类(即你是正确的) - 我想打印一条消息.我是.
但如果课程不匹配,我希望显示一条消息,说明猜错了.它更容易显示.所以这是我的jQuery:
$(document).ready(function(){
$('.left').hide();
$('.right').hide();
$('.happy').click(function(){
$('.left').show();
$('.right').show();
if($(this).hasClass('happy') && $("img").hasClass('happy')){
$('h2').replaceWith("<h2>You are correct!</h2>");
}else if(!$('img').hasClass('happy')){
alert("LOL");
};
});
});
Run Code Online (Sandbox Code Playgroud)
我的代码的第一部分,如果按下按钮则显示h2 - 有效.但第二部分 - 否则if(! $('img').hasClass('happy')) - 不会.为什么?
我的HTML:http://jsfiddle.net/WEAt6/3/
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>
gzzzz
</title>
</head>
<body>
<div id="container">
<div id="answers">
<div class="sadness">
<p class="feelings">SADNESS</p>
</div>
<div class="anger">
<p class="feelings">ANGER</p>
</div>
<div class="surprise">
<p class="feelings">SURPRISE</p>
</div>
<div class="fear">
<p class="feelings">FEAR</p>
</div>
<div class="disgust">
<p class="feelings">DISGUST</p>
</div>
<div class="contempt">
<p class="feelings">CONTEMPT</p>
</div>
<div class="happy">
<p class="feelings">HAPPINESS</p>
</div>
</div>
<div class="thegame">
<div class="pic">
<img class="left" src="http://upload.wikimedia.org/wikipedia/commons/5/55/Happy_man.jpg"/ >
</div>
<div class="pic">
<img class="happy" src="http://upload.wikimedia.org/wikipedia/commons/5/55/Happy_man.jpg"/ >
</div>
<div class="pic">
<img class="right" src="http://upload.wikimedia.org/wikipedia/commons/5/55/Happy_man.jpg"/ >
</div>
</div>
<div id="score">
<h2></h2>
</div>
</div>
</body>
<script src="jQuery.js"></script>
<script src="stuff.js"></script>
</html>
?
Run Code Online (Sandbox Code Playgroud)
你的if陈述的逻辑有两个条件.所以它可能$(this).hasClass('happy')是假的,但是$("img").hasClass('happy')(在else if)中是真的,因此if块和else if块的代码都不会运行.
几个旁注:
$("img").hasClass('happy')会告诉你是否任何 img文件中有类happy.你没有引用你的HTML,但似乎值得一提.因此,由于您确实拥有该类的图像,因此它始终是真的.如果你想检查一个特定的图像,或者给它第二个类并使用$("img.theOtherClass").hasClass("happy")或你可以按位置:$("img").first().hasClass("happy")第一个,$("img").eq(1).hasClass('happy')第二个(eq基于0),等等.
$('h2').replaceWith("<h2>You are correct!</h2>");替换h2另一个,新的h2.改变其内容可能更好:$('h2').html('You are correct!');.
上面#2中的代码(包括你和我的代码)将更改文档中的所有 h2元素.也许,这很好,但似乎值得强调.您可以考虑$("#score h2").html("You are correct!");是否只想用元素更改元素内部的元素id "score".