定义函数并在select语句中用作onchange,而不是直接使用.change(function)

Define function and use as onchange in the select statement instead of directly using .change(function)

本文关键字:function change 函数 select 语句 onchange 定义      更新时间:2023-09-26

定义一个函数并将其用作select语句中的onchange,而不是直接使用.change(function).有什么错

我想用这个来显示一个不同的组合框:

     function MetricLayerShowHide (){           
            var type = $(this).val();
              if( type !==''){
                 $('.content').hide();
                 $('#'+type).show();
              }
      }

<select name="MetricType" id="MetricType" onchange="MetricLayerShowHide();" >
    <option value=CD>CD</option>
     <option value=HT>HT</option>
     <option value=Profile>Profile</option>
  </select>
   <div id="CD" style ="display: none" class ="content">
       <SELECT NAME="LayerList" id="layer1">
      </SELECT>
    </div>

而不是

         $(function(){
        $('#MetricType').change(function(){
            var type = $(this).val();
              if( type !==''){
                 $('.content').hide();
                 $('#'+type).show();
              }
        });
     });

不过这是有效的。

我哪里错了?

问题是,当您调用函数时,this不再是元素。您正在全局上下文中调用函数,因此this将是函数内的window对象。

您可以使用call方法调用元素作为上下文的函数:

onchange="MetricLayerShowHide.call(this);"

演示:http://jsfiddle.net/Guffa/co5ymkyk/

问题很简单:this在调用函数时不再引用您期望的元素。

HTML:

<form>
    <select name="MetricType" id="MetricType" >
    <option value=CD>CD</option>
    <option value=HT>HT</option>
    <option value=Profile>Profile</option>
</select>
</form>
<div class="content" id="CD">CD</div>
<div class="content" id="HT">HT</div>
<div class="content" id="Profile">Profile</div>

脚本:

$(function(){
        $('#MetricType').change(function(){
           var type = $(this).val();
              if( type !==''){
                 $('.content').hide();
                 $('#'+type).show();
              }});
     });

CSS:

.content { display: none; }

JSFiddle演示在这里。

附带说明一下,这是基于您作为评论发布的JSFiddle。您由于缺少一个括号而创建了一个新问题。

请更新你的问题,因为这个答案断章取义@古法实际上答对了你的问题。