javascript JQuery:onchange 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15030526/
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-10-26 23:12:55  来源:igfitidea点击:

JQuery: onchange event

javascriptjqueryhtml

提问by O1DMBFan

Trying to show/hide a text file based on the users selection in a select. I believe my problem is with the if statement.

试图根据用户在选择中的选择来显示/隐藏文本文件。我相信我的问题出在 if 语句上。

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>

<script>
$(document).ready(function(){
  $("#drpStatus").change(function(){
    if( $(this).val() == 'Married'){
      $("#txtSpouse").show();
    else
      $("#txtSpouse").hide();
  });
});
</script>

</head>

<body>
<input type="text" id="txtSpouse" style="display:none">
<select name="drpStatus" id="drpStatus">
            <option value="Single" selected="selected">Single</option>
            <option value="Dating">Dating</option>
            <option value="Married">Married</option>
          </select>
</body>

</html>

回答by Travis J

Simple syntax error, you have an extra {after your if. Remove it and this works.

简单的语法错误,你{if. 删除它,这有效。

demo: http://jsfiddle.net/yNqfM/

演示:http: //jsfiddle.net/yNqfM/

js

js

$("#drpStatus").change(function(){
 if( $(this).val() == 'Married') /*removed the {*/
  $("#txtSpouse").show();
 else
  $("#txtSpouse").hide();
});

回答by Jeff Shaver

You made a syntax error. you added a { after your if statement but you never end it. you can either remove it, or you can change it to } else { /** code **/ }

你犯了一个语法错误。您在 if 语句后添加了 { 但您从未结束它。您可以删除它,也可以将其更改为 } else { /** code **/ }

回答by Jeff Shaver

Try below code : Link for jsFiddle http://jsfiddle.net/kbSrR/

试试下面的代码:jsFiddle的链接http://jsfiddle.net/kbSrR/

 $(function(){
    $("#drpStatus").change(function () {
        if ($(":selected",$(this)).text() == 'Married') 
            $("#txtSpouse").show();
            else $("#txtSpouse").hide();
        });
    });