【问题标题】:Calling Javascript from a html form从 html 表单调用 Javascript
【发布时间】:2010-10-15 13:44:08
【问题描述】:

我的问题和示例基于 Jason 在 this 问题中的回答

我试图避免使用eventListener,而只是在单击提交按钮时调用handleClick onsubmit

我的代码完全没有任何反应。

为什么没有调用handleClick

<html>
  <head>
    <script type="text/javascript">
      function getRadioButtonValue(rbutton)
      {
        for (var i = 0; i < rbutton.length; ++i)
        { 
          if (rbutton[i].checked)
            return rbutton[i].value;
        }
        return null;
      }

      function handleClick(event)
      {
        alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
    <form name="myform" onSubmit="JavaScript:handleClick()">
      <input name="Submit"  type="submit" value="Update" onClick="JavaScript:handleClick()"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>
</body>
</html>

编辑:

请不要将框架作为解决方案。

以下是我对代码所做的相关更改,这些更改会导致相同的行为。

      function handleClick()
      {
        alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye">;
      <input name="Submit"  type="submit" value="Update" action="JavaScript:handleClick()"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>

【问题讨论】:

  • 如果表单元素没有 sandbox="allow-scripts" 属性,那么这些方法都不会在现代浏览器中工作。 w3schools.com/Tags/att_iframe_sandbox.asp
  • @MuhammadUmer - AFAIK,当您明确创建作为沙盒的 iframe 时,需要沙盒属性。如果您的 HTML iframe 不包含“沙盒”属性,或者您没有 iframe,那么这些限制如何生效?
  • FWIW,这个问答的寓意是“当它不工作时,从你的代码中删除一些东西,直到你找到什么工作,然后回到你的错误”。如果警报被简化为alert("Favorite weird creature");,OP 会发现它有效(出现警报),然后就会知道他在...getRadioButtonValue(..) 的语法中有一些问题。从有效到无效的连续迭代可能会将问题隔离到this["whichThing"] 没有返回值。一个更简单的问答:将其替换为document.aye.whichThing。解决了。​​

标签: javascript html forms dom-events


【解决方案1】:

onclick="..onsubmit=".. 声明中删除javascript:

javascript: 前缀仅用于href="" 或类似属性(与事件无关)

【讨论】:

    【解决方案2】:

    在这段代码中:

    getRadioButtonValue(this["whichThing"]))
    

    你实际上并没有得到对任何东西的引用。因此,getradiobuttonvalue 函数中的单选按钮未定义并引发错误。

    编辑 要从单选按钮中获取值,请获取 JQuery 库,然后使用:

      $('input[name=whichThing]:checked').val() 
    

    编辑 2 由于希望重新发明轮子,这里是非 Jquery 代码:

    var t = '';
    for (i=0; i<document.myform.whichThing.length; i++) {
         if (document.myform.whichThing[i].checked==true) {
             t = t + document.myform.whichThing[i].value;
         }
    }
    

    或者,基本上,修改原始代码行以这样阅读:

    getRadioButtonValue(document.myform.whichThing))
    

    编辑 3 这是你的作业:

          function handleClick() {
            alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
            //event.preventDefault(); // disable normal form submit behavior
            return false; // prevent further bubbling of event
          }
        </script>
      </head>
    <body>
    <form name="aye" onSubmit="return handleClick()">
         <input name="Submit"  type="submit" value="Update" />
         Which of the following do you like best?
         <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
         <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
         <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>
    

    请注意以下内容,我已将函数调用移至表单的“onSubmit”事件。另一种方法是将您的提交按钮更改为标准按钮,并将其放入按钮的 OnClick 事件中。我还删除了函数名前面不需要的“JavaScript”,并在函数输出的值上添加了一个显式的 RETURN。

    在函数本身中,我修改了表单的访问方式。结构是: document.[THE FORM NAME].[THE CONTROL NAME] 来解决问题。由于您重命名了 from aye,因此您必须更改 document.myform。记录。是的。此外,document.aye["whichThing"] 在这种情况下是错误的,因为它需要是 document.aye.whichThing

    最后一点,我注释掉了 event.preventDefault();。此示例不需要该行。

    编辑 4 只是为了清楚。 document.aye["whichThing"] 将为您提供对选定值的直接访问权限,但 document.aye.whichThing 让您可以访问单选按钮的集合,然后您需要检查。由于您使用“getRadioButtonValue(object)”函数来遍历集合,因此您需要使用 document.aye.whichThing

    看看这个方法的区别:

    function handleClick() {
       alert("Direct Access: " + document.aye["whichThing"]);
       alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
       return false; // prevent further bubbling of event
    }
    

    【讨论】:

    • 我还能如何获得单选按钮的值?
    • 使用 getRadioButtonValue(document.myform['whichThing'])。我在此略过 javascript OO,但当函数是对象范围的一部分时,“this”用于指代对象。您的示例使用顶级函数并且没有对象。
    • 啊,这也失败了。你能再举个例子吗?
    • 请不要推荐 jquery。我想在没有图书馆帮助的情况下理解这一点。
    • 如果您不希望引用 JQuery(或其他库),那么您应该在 OP 中说明。坦率地说,在可用时不使用库是很疯狂的
    【解决方案3】:

    您可以使用带有

    的 javascript url 表单
    <form action="javascript:handleClick()">
    

    或使用 onSubmit 事件处理程序

    <form onSubmit="return handleClick()">
    

    在后面的表单中,如果你从handleClick返回false,将会阻止正常的提交过程。如果您希望浏览器遵循正常的提交过程,则返回 true。

    按钮中的 onSubmit 事件处理程序也因Javascript: 部分而失败

    编辑: 我刚刚尝试了这段代码,它可以工作:

    <html>
      <head>
        <script type="text/javascript">
    
          function handleIt() {
            alert("hello");
          }
    
        </script>
      </head>
    
    <body>
        <form name="myform" action="javascript:handleIt()">
          <input name="Submit"  type="submit" value="Update"/>
        </form>
    </body>
    </html>
    

    【讨论】:

    • 这两个我都试过了,都没有任何区别,无论我尝试什么都没有显示警报。
    • Joshxtothe4 是对的......他的警报失败了,主要不是因为他的函数没有被调用,也不是因为它被调用了两次,因为 javascript 事件调用加倍,而是因为 this[" whichThing"] 构造导致错误。
    【解决方案4】:

    在您的编辑版本中有几处需要更改:

    1. 您接受了使用document.myform['whichThing'] 的建议有点过于字面意思了。您的表单名为“aye”,因此访问 whichThing 单选按钮的代码应使用该名称:`document.aye['whichThing']。

    2. &lt;input&gt; 标签没有 action 属性。请改用onclick&lt;input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/&gt;

    3. 在浏览器中获取和取消 Event 对象是一个非常复杂的过程。它因浏览器类型和版本而异。 IE 和 Firefox 处理这些事情的方式非常不同,所以一个简单的event.preventDefault() 将不起作用......事实上,甚至可能不会定义事件变量,因为这是来自标签的 onclick 处理程序。这就是为什么上面的斯蒂芬如此努力地提出一个框架的原因。我知道你想知道机制,我推荐谷歌。在这种情况下,作为一种简单的解决方法,请在 onclick 标记中使用return false,如上面的数字 2 所示(或按照 stephen 的建议从函数中返回 false)。

    4. 由于#3,除掉处理程序中的警报语句之外的所有内容。

    代码现在应该如下所示:

    function handleClick()
          {
            alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
          }
        </script>
      </head>
    <body>
        <form name="aye">
          <input name="Submit"  type="submit" value="Update" onclick="handleClick();return false"/>
          Which of the following do you like best?
          <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
          <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
          <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
        </form>
    

    【讨论】:

    • 感谢您的所有帮助。我选择了斯蒂芬斯的回答,因为我觉得他做了很多工作,但你的回答也很有帮助。干杯。
    【解决方案5】:

    Miquel (#32) 的漂亮例子应该补充:

    <html>
     <head>
      <script type="text/javascript">
       function handleIt(txt) {   // txt == content of form input
        alert("Entered value: " + txt);
       }
      </script>
     </head>
     <body>
     <!-- javascript function in form action must have a parameter. This 
        parameter contains a value of named input -->
      <form name="myform" action="javascript:handleIt(lastname.value)">  
       <input type="text" name="lastname" id="lastname" maxlength="40"> 
       <input name="Submit"  type="submit" value="Update"/>
      </form>
     </body>
    </html>
    

    表格应该有:

    <form name="myform" action="javascript:handleIt(lastname.value)"> 
    

    【讨论】:

    • 表格应该有:
    【解决方案6】:

    您的代码中的所有内容似乎都很完美,除了 handleClick() 不起作用,因为该函数在其函数调用调用中缺少参数(但其中的函数定义有一个导致函数不匹配发生的参数) .

    以下是计算所有学期总分和相应成绩的示例工作代码。它演示了在 html 文件中使用 JavaScript 函数(调用)并解决了您面临的问题。

    <!DOCTYPE html>
    <html>
    <head>
        <title> Semester Results </title>
    </head>
    <body>
        <h1> Semester Marks </h1> <br> 
        <script type = "text/javascript">
            function checkMarks(total)
            {
                document.write("<h1> Final Result !!! </h1><br>");
                document.write("Total Marks = " + total + "<br><br>");
                var avg = total / 6.0;
                document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
                if(avg >= 90)
                    document.write("Grade = A");
                else if(avg >= 80)
                    document.write("Grade = B");
                else if(avg >= 70)
                    document.write("Grade = C");
                else if(avg >= 60)
                    document.write("Grade = D");
                else if(avg >= 50)
                    document.write("Grade = Pass");
                else
                    document.write("Grade = Fail");
           }
        </script>
        <form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
            Semester 1:  <input type = "text" id = "s1"/> <br><br>
            Semester 2:  <input type = "text" id = "s2"/> <br><br>
            Semester 3:  <input type = "text" id = "s3"/> <br><br>
            Semester 4:  <input type = "text" id = "s4"/> <br><br>
            Semester 5:  <input type = "text" id = "s5"/> <br><br>
            Semester 6:  <input type = "text" id = "s6"/> <br><br><br>
            <input type = "submit" value = "Submit"/>
        </form>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多