我想动态更改“form.submit();”的任何实例出现在 onchange 函数中,将某些 select 元素发送到 $('form').submit();以便为表单本身触发提交事件。
以下是此类选择列表的示例,其中 onchange 函数需要更新:
<td class="form-field selectinput" align="left" valign="left" style="width: 90px;" title="Select status type">
<select class="filterlist" name="cStatus" tabindex="5" style="width: 90px;" onchange="form.submit();">
<option value="" title="[All]">[All]</option>
<option value="A" title="Authorised">Authorised</option>
<option value="C" selected="" title="Cancelled">Cancelled</option>
<option value="U" title="Declined">Declined</option>
<option value="R" title="Requested">Requested</option>
<option value="T" title="Taken">Taken</option>
<option value="W" title="Withdrawn">Withdrawn</option>
</select>
</td>
我在页面的标题部分插入以下内容来尝试更新该功能:
$(document).ready(function(){
$(function() {
$('select').each(function() {
var txt = this.onchange ;
alert(txt);
var patt=/form.submit()/g;
var result=patt.test(txt);
if (result) {
var txt = txt.replace('form.submit()',"");
this.onchange = eval(txt);
}
});
});
});
警报消息出现:
function onchange(event) { form.submit(); } Blockquote
然后控制台日志显示以下错误:
Uncaught TypeError: Object function onchange(event) { form.submit(); } has no method 'replace'
我实际上可以让它与以下内容一起工作:
this.onchange = function() { $('form').submit(); }
但是在某些情况下,onchange 除了 form.submit(); 之外还有其他代码;如:
form.submit();form.iYear.disabled=true;form.cGroupItem.disabled=true;
所以我不想替换整个函数本身,而是删除“form.submit();”并将其替换为 '$('form').submit();',因此上面的内容将显示为:
$('form').submit();form.iYear.disabled=true;form.cGroupItem.disabled=true;
我尝试在不同的地方使用 toString() 和 eval(),但每当我尝试编辑字符串 txt 时,我总是收到对象没有方法错误。
有什么想法吗?
最佳答案
不用进行时髦的评估和替换,只需尝试以下操作:
...
if (result) {
this.onchange = function(){}; //empty function
}
...
关于javascript - onchange 函数动态更新的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10915190/