简体   繁体   English

Javascript函数因全局变量而失败

[英]Javascript function fails with global vars

I have used this function to submit to any url or 'self', with or without a querystring, many times without any problems. 我多次使用此函数提交到任何url或“ self”(带有或不带有查询字符串),没有任何问题。

function submitu(url, q) {
 var frm = document.<?php echo $formname ?>;
 if (url == '') {url = '<?php echo $thispage?>'; }
 frm.action = url+q; frm.submit(); }

If I try to move the PHP vars outside the function, as below, it stops working (frm undefined error) 如果我尝试将PHP var移到函数外部,如下所示,它将停止工作(frm未定义错误)

var thispage = '<?php echo $thispage?>';
var frm = document.<?php echo $formname?>;
function submitu(url, q) {
 if (url == '') {url = thispage;}
 frm.action = url+q; frm.submit();}

I also tried var frm = document.forms['']; 我也尝试了var frm = document.forms [''];

I don't have any other conflicting javascript, 我没有其他冲突的JavaScript,

(1). (1)。 Can anyone tell me why this is not working? 谁能告诉我为什么这不起作用? (2). (2)。 And why the first method also fails if the function is placed inside and at the top of the jquery $(function() {.....} ready function? 为什么将函数放在jquery $(function(){.....} ready函数的内部和顶部时,第一种方法也会失败?

Many thanks 非常感谢

It fails because when outside the function, var frm = document.formname; 失败是因为在函数外时,var frm = document.formname; will be run immediately when the page loads, ie before the form element has actually been constructed, so you get 'undefined'. 将在页面加载时立即运行,即在实际构造form元素之前运行,因此您会获得“ undefined”。 When inside the function, it is only run when the function is run, by which time the DOM is complete and it can find it. 在函数内部时,仅在运行函数时才运行它,届时DOM完成并且可以找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM