如果第一个表单名称返回时未定义,如何测试第二个表单名称

How do I test for a second form name if the first form name comes back undefined?

本文关键字:表单 测试 何测试 第二个 未定义 返回 第一个 如果      更新时间:2023-09-26

我希望能够测试是否定义了表单,这意味着它找到了一个名为"data"的表单我们该怎么做?

然后,如果没有找到,我可以测试其他表单名称,并在该命名表单上设置操作。

function edit_OnClick() {
    var theForm = window.document.forms['data'];
    theForm.action = "checkout.asp";
    theForm.submit();
    return false;
}

在stackoverflow发布后续消息可以吗?

这是我根据你的建议想出的,但并没有像我计划的那样改变。

    function edit_OnClick() {
        var theForm = window.document.forms['data'];
        if ( typeof ( theForm !== "undefined" )) {
            theForm.action = "checkout.asp";
            theForm.submit();
            return false;
        }else {
        var theForm = window.document.forms['form_bml'];
            theForm.action = "checkout.asp";
            theForm.submit();
            return false;
        }
    }
if ( theForm ) { .. }

应该足够了。如果你想安全起见,你可以选择

if ( typeof ( theForm ) !== "undefined" ) { ... }

您可以使用:

var theForm = document.forms['data'];
if (theForm) {
  // do stuff
} else {
  theForm = document.forms['form_bml'];
  if (theForm) {
    // do other stuff
  }
}

如果两者的操作相同,则:

var theForm = document.forms['data'] || document.forms['form_bml'];
if (theForm) {
  // do stuff
}