HTML表单提交按钮不运行与之关联的OnSubmit脚本 [英] HTML-form submit button not running the OnSubmit script associated with it

查看:83
本文介绍了HTML表单提交按钮不运行与之关联的OnSubmit脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Chrome扩展,到目前为止我只是测试一些东西。这个扩展的HTML是这样的:

 <!doctype html> 
< html>
< head>
< title>标题< / title>
< script src =processform.js>< / script>
< / head>
< body>
< form name =myformonSubmit =ExampleJS()>
名字:< input type =textid =fnamename =firstname/>< br />
姓氏:< input type =textid =lnamename =lastname/>< br />
< input name =Submittype =submitvalue =Update/>
< / form>
< / body>
< / html>

processform.js文件是这样的:

  function ExampleJS(){
var jFirst = document.getElementById(fname).value;
var jLast = document.getElementById(lname).value;
alert(你的名字是:+ jFirst ++ jLast);
}

当我按下提交按钮时,警告不会出现。

解决方案

由于其内容安全政策,因此无法在Chrome扩展程序中使用内嵌代码,并且在元素中将 onsubmit 设置为内嵌。



一个基于jQuery的解决方案(您需要将jQuery扩展名并添加到页面中,但这不会造成任何损害):

< pre $ // processform.js
$(document).ready(function(){
//从JS绑定,而不是内联
$(表单)。submit(ExampleJS);
});

一个纯粹的JavaScript解决方案是:

 //从JS绑定,而不是内联
document.forms [myform]。addEventListener('submit',ExampleJS);
});


I'm making a chrome extension, and so far I'm just testing some things. The HTML for the extension is this:

<!doctype html>
<html>
  <head>
    <title>Title</title>
    <script src="processform.js"></script>
  </head>
  <body>
    <form name="myform" onSubmit="ExampleJS()">
         First name: <input type="text" id="fname" name="firstname" /><br />
         Last name:  <input type="text" id="lname" name="lastname" /><br />
        <input name="Submit"  type="submit" value="Update" />
    </form>
  </body>
</html>

The processform.js file is this:

function ExampleJS(){
    var jFirst = document.getElementById("fname").value;
    var jLast = document.getElementById("lname").value;
    alert("Your name is: " + jFirst + " " + jLast);
}

When I press the submit button the alert doesn't appear.

解决方案

You cannot use inline code in a Chrome extension due to its Content Security Policy, and setting onsubmit in the element counts as inline.

A jQuery-based solution (you will need to include jQuery with the extension and add it to the page, but there's no harm in that):

// processform.js
$(document).ready(function(){
  // Bind from JS, not inline
  $("form").submit(ExampleJS);
});

A pure JavaScript solution would be:

// processform.js
document.addEventListener('DOMContentLoaded', function(){
  // Bind from JS, not inline
  document.forms["myform"].addEventListener('submit', ExampleJS);
});

这篇关于HTML表单提交按钮不运行与之关联的OnSubmit脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆