为什么我无法调用使用外部库的脚本标记中定义的用户函数

时间:2017-05-23 05:08:06

标签: javascript html

<html>
<head>
<title>Register</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="css/style.css"/>
<!-- Include JS File Here -->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js">

    function dispatchRegister() {
       //Some AWS lib code 
    }
</script>
</head>
<body>
<div class="container">
<div class="main">
<h2>Put Your credentials</h2>
<form id="form_id" method="post" name="myform">
<label>registerUsername</label>
<input type="text" name="registerUsername" id="registerUsername"/>
<label>registerPassword</label>
<input type="text" name="registerPassword" id="registerPassword"/>
<label>registerEmail</label>
<input type="text" name="registerEmail" id="registerEmail"/>
<input type="button" value="Register" id="submit" onclick="dispatchRegister()"/>
</form>
</body>
</html>

我收到错误&#34; 未捕获的ReferenceError:未定义dispatchRegister &#34; 我怀疑功能不在全球范围内,但我如何解决这个问题呢?

2 个答案:

答案 0 :(得分:2)

Script-tags documentation说明了src-attribute:

此属性指定外部脚本的URI;这可以用作直接在文档中嵌入脚本的替代方法。 如果脚本元素指定了src属性,则不应在其代码中嵌入脚本

因此,删除src并将外部脚本添加为单独的脚本标记:

&#13;
&#13;
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js"></script>
<script>
  function dispatchRegister() {
    console.log("Here I am!");
  }
</script>

<input type="button" value="Register" id="submit" onclick="dispatchRegister()" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

因为您将src设置为src="https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js"

尝试像这样添加dispatchRegister(),它会起作用:

<script>
function dispatchRegister() {
   //Some AWS lib code 
}
</script>