gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:18:28 25 4
gpt4 key购买 nike

定义一个函数并在 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 method以元素作为上下文调用函数:

onchange="MetricLayerShowHide.call(this);"

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

关于javascript - 定义函数并在select语句中作为onchange使用,而不是直接使用.change(function),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com