即使在引用后也无法访问外部Jscript文件
Not able to access external Jscript File even after referencing?
我是一个初学者,正在尝试我的第一个程序,在script标记的scr属性中添加外部jscript文件,按照我搜索的所有步骤进行,但它没有按应有的方式工作。有人能帮我做这个吗?
- 我有一个aspx表单,一键点击调用内部javascript函数。我还有一个按钮onclick调用外部.js文件函数
这是我的aspx代码
<head runat="server">
<script type="text/javascript" language="javascript" src="ExternalJScript.js">
function Myfunction()
{
document.getElementById("htmlbutton").innerHTML = "This is Button from Javascript function";
alert("Hi Function Called from Javascript");
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<button type="button" id="htmlbutton" onclick="Myfunction()">This is html button</button><br />
<button type="button" id="Button1" onclick="ExternalJSFileFunction()" value="Call File">HI</button>
</div>
</form>
这是我的.js代码
ExternalJSFileFunction()
{
alert("I m from external file");
}
外部脚本的脚本标记之间不应该有代码。尝试将其更改为:
<head runat="server">
<script type="text/javascript" language="javascript" src="ExternalJScript.js"></script>
<script type="text/javascript">
function Myfunction()
{
document.getElementById("htmlbutton").innerHTML = "This is Button from Javascript function";
alert("Hi Function Called from Javascript");
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<button type="button" id="htmlbutton" onclick="Myfunction()">This is html button</button><br />
<button type="button" id="Button1" onclick="ExternalJSFileFunction()" value="Call File">HI</button>
</div>
</form>
此外,Language属性已弃用,不需要
编辑
这是因为你试图调用的函数实际上不是一个函数,因为没有使用function关键字。更改外部文件,使其为:
function ExternalJSFileFunction()
{
alert("I m from external file");
}
然后它将工作
此外,还有一些其他提示:
如果你使用的是HTML5doctype,你也可以去掉<script>
元素上的type属性
也要将你的大括号与函数或条件放在同一行,这样做:
function ExternalJSFileFunction() {
但不是:
function ExternalJSFileFunction()
{
您几乎应该总是将脚本添加到页面的末尾,就在性能的关闭</body>
标记之前
使用onclick
属性也不是附加事件处理程序的推荐方式,您应该使用正确的addEventListener()
方法。如果您需要支持<=IE8您需要使用IE的旧事件API。使用JS库。像jQuery一样,可以真正帮助解决这类问题。
外部JavaScript文件中的函数定义不正确。
它应该是这样的(我添加了function
关键字)。
function ExternalJSFileFunction()
{
alert("I m from external file");
}
你还需要做出丹韦尔曼在回答中建议的改变。
相关文章:
- Javascript从匿名函数访问外部对象属性
- 在nodejs中使用require来访问外部javascript文件
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- jQuery:如何访问外部变量
- 从jQuery.ech()函数访问外部作用域
- 我可以't访问外部javascript文件中的freemarker变量
- 是否有任何方法可以访问外部范围's变量
- 访问外部调用方函数参数
- 即使在引用后也无法访问外部Jscript文件
- JQuery 承诺:访问外部变量或将结果传递给 .done 内部的 IIFE
- 从内联 html 页面访问外部 JS 变量
- 咕噜声:访问外部文件中的 YAML 符号
- 从 angularjs 控制器访问外部 JavaScript 函数和类
- Chrome 应用程序使用 JavaScript / jQuery / AngularJS 访问外部资源
- 使用 JavaScript 和/或 jQuery 访问外部 HTML 正文的宽度和高度
- 评估是否可以访问外部函数
- 如何从传入的预定义回调访问外部变量
- 为什么我无法使用codeigniter访问外部javascript文件,即使它们被加载了
- 从 js obj 数组访问外部 js obj 属性
- 如何访问外部JavaScript文件中的DOM对象