![](/img/trans.png)
[英]Why my props action doesn't work in an “if” statement in “onClick”, but it works outside the “if” statement?
[英]Why doesn't my “IF” statement work? (Works if commented out)
所以我是jQuery的新手,我无法弄清楚为什么我的IF语句不起作用,尽管代码在我注释掉IF时起作用。 请帮帮我...谢谢!
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("tr.anon").hide();
$("#hideID").change(function(){
// IF ($("#hideID option[value='no']").text()){
$("tr.anon").show();
// alert($this).find("option:selected").text()+' clicked!');
// }ELSE{
// $("tr.anon").hide();
// }
});
});
</script>
</head>
<body>
<p>Would you like to remain anonymous? <select id="hideID">
<option value="yes">Yes</option>
<option value="no">No</option>
</select></p>
<table border="1px">
<tr class="anon">
<td>Enter your name:</td>
<td><input class="field2" type="text" /></td>
</tr>
</table>
</body>
</html>
感谢您的快速反馈...我已将我的代码调整为以下但仍然无效。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script><script type="text/javascript">
$(document).ready(function(){
$("tr.anon").hide();
$("#hideID").change(function(){
// if ($("#hideID option[value='no']").text()){
$("tr.anon").show();
// alert(#hideID).find("option:selected").text()+' clicked!');
// }else{
// $("tr.anon").hide();
// }
});
});
</script>
</head>
<body>
<p>Would you like to remain anonymous?
<select id="hideID">
<option value="yes">Yes</option>
<option value="no">No</option>
</select></p>
<table border="1px">
<tr class="anon">
<td>Enter your name:</td>
<td><input class="field2" type="text" /></td>
</tr>
</table>
</body>
</html>
你不应该使用CAPS进行IF
和ELSE
!
if
和else
必须是小写的。 Javascript区分大小写。
另外,我不认为这里的if
子句正在做你想要的。 您正在测试#hideID option[value='no']
的真实性,它将始终评估为true。 我想你真的想检查是否选择了'no'值。 此外,您只是简单地切换可见性,因此jQuery的切换方法在这里更合适。
试试这个:
$('tr.anon').toggle( $("#hideID option:selected").val() === "no" );
还要确保你没有在大写字母中写下'if ... else'语句!
Javascript区分大小写, if
和else
应该是小写的。
此外,您正在检查$("#hideID option[value='no']").text()
是否真实。 如果文本不是空字符串,那么你将沿着真正的道路走下去,这是你的意图吗?
好吧,让我们试试这个...我修复了脚本工作。 您可以看到更改。
<script type="text/javascript">
$(document).ready(function(){
$("tr.anon").hide();
$("#hideID").change(function(){
if ($("#hideID").val()=="no"){
$("tr.anon").show();
alert($(this).find("option:selected").text() + ' clicked!');
} else {
$("tr.anon").hide();
$("#textFieldID").val("");
}
});
});
</script>
由于您只有两个值,因此可以使用:
演示: http : //jsfiddle.net/ThinkingStiff/eqxCa/
脚本:
$( 'tr.anon' ).hide();
$( '#hideID' ).change( function() { $( 'tr.anon' ).toggle(); } );
改为值==='不'。 =用于赋值,==和===是比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.