onchange事件显示目标元素的所有文本值,为什么?

时间:2014-10-21 07:23:01

标签: javascript jquery

考虑一下:

<!DOCTYPE html>
<html>
<head>
   <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
   <script>

      $(function(){

           $("select").change(function(){

                 var val = $(this).val();
                 var text = $(this).text();

                 // That's fine
                 alert(val);

                 // But it's not. It alerts both Value 1 and Value 2
                 alert(text);
           });
      }); 

   </script>
</head>
<body>

 <select>
    <option value="val_1">Value 1</option>
    <option value="val_2">Value 2</option>
 </select>


</body>
</html>

onchange事件发生时,它会警告目标option元素(val_1或val_2)的正确值。没关系。

但选项的文字存在问题。这应该警告值1或值2,但不是两者!那么问题是什么?当只处理一个目标选项元素时,为什么它会警告这两个值?

&#13;
&#13;
  $(function(){

           $("select").change(function(){

                 var val = $(this).val();
                 var text = $(this).text();

                 // That's fine
                 alert(val);

                 // But it's not. It alerts both Value 1 and Value 2
                 alert(text);
           });
      }); 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>

 <select>
    <option value="val_1">Value 1</option>
    <option value="val_2">Value 2</option>
 </select>


</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

在您的更改活动中,this引用<select>元素,而非选定的<option>,因此在选择中调用.text()将显示所有选项。

要获取所选的选项文本:

var text = $(this).find("option:selected").text();

$(function(){

           $("select").change(function(){

                 var val = $(this).val();
                  var text = $(this).find("option:selected").text();

                 // That's fine
                 alert(val);

                 // But it's not. It alerts both Value 1 and Value 2
                 alert(text);
           });
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
 
</head>
<body>

 <select>
    <option value="val_1">Value 1</option>
    <option value="val_2">Value 2</option>
 </select>


</body>
</html>