Javascript 将onchange指定给对象并传递参数
因此,我有以下JavaScript:Javascript 将onchange指定给对象并传递参数,javascript,Javascript,因此,我有以下JavaScript: <script language=JavaScript> function reload(form){ var val=form.profile.options[form.profile.options.selectedIndex].value; self.location='?profile=' + val ; } function init(){ var form = d
<script language=JavaScript>
function reload(form){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;
</script>
但是如果我有更多的表格呢?或者我想在多个具有不同表单名称的页面上重复使用重新加载
不过,我希望避免在HTML标记中设置onchange:
onchange="reload(this.form)"
如果可能的话
谢谢
但是如果我有更多的表格呢
您可以将相同的函数分配给表单中的所有配置文件
元素,并使用this
引用函数中接收更改事件的元素
<script type="text/javascript">
function reload(){
// In here, "this" is the element that received the event
var val = this.options[ this.options.selectedIndex ].value;
self.location='?profile=' + val ;
}
function init(){
var len = document.forms.length;
while( len-- ) {
document.forms[ len ].profile.onchange = reload;
}
}
window.onload = init;
</script>
函数重载(){
//在这里,“this”是接收事件的元素
var val=this.options[this.options.selectedIndex].value;
self.location='?profile='+val;
}
函数init(){
var len=document.forms.length;
而(len--){
document.forms[len].profile.onchange=reload;
}
}
window.onload=init;
您可以创建一个函数,为重载函数返回函数(闭包)
function reload(form){
return function(){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;
哈,我无法决定选择哪个答案……:)我喜欢Patricks的解决方案,它很简单,我不知道这个。但是你也给出了一个返回函数的好例子,这也很好(所有的JS业务对我来说都是新的)…@pulgium:Rocket的这个解决方案肯定也很有效。它需要更多的开销,但有一定的极客冷静o) @pulgium:@patrick's可能是这里更好的选择。因为与每次创建一个新函数相比,您只使用了一个函数。
function reload(form){
return function(){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;