为什么我的"IF"语句不起作用?(如果注释掉则有效)



所以我是新的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?&nbsp;<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?&nbsp;
<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>

不应该在IFELSE中使用CAPS !!

ifelse必须为小写。Javascript是区分大小写的

也,我不认为if子句在这里做你想要的。您正在测试#hideID option[value='no']的真实性,它将始终评估为真。我认为你真的想检查是否选择了'no'值。此外,您只是在切换可见性,因此jQuery的toggle方法在这里更合适。

试试这个:

$('tr.anon').toggle( $("#hideID option:selected").val() === "no" );

还要确保你没有写" if…"Else语句用大写!

Javascript是大小写敏感的,你的ifelse应该是小写的。

同时,你正在检查$("#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(); } );

改为value==='no'。=是赋值,==和===是比较。

相关内容

最新更新