![](/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.