导入.js脚本时,单击时没有响应

No response on click when .js script is imported

本文关键字:响应 单击 js 脚本 导入      更新时间:2023-09-26

此代码运行良好:

HTML

<form>
  <input type="radio" name="category" value="doctor" /> Doctor
  <input type="radio" name="category" value="police" checked /> Policia
</form>

JS-

var category = null;
$("input[name='category']").click(function() {
    category = this.value;
    alert(category);
});

当您单击单选按钮时,会立即收到响应。但是,当您在外部javascript文件中有相同的脚本时。它不起作用。当两者都在一个html文件中时,上面的代码就可以工作了。

如果我在不同的文件中做同样的事情,比如index.html和jscript.js

index.html

<html>
<head>
<script type="text/javascript" src="jscript.js"></script>
</head>
<body>
  <form>
  <input type="radio" name="category" value="doctor" /> Doctor
  <input type="radio" name="category" value="police" checked /> Policia
</form>
</body>
</html>

jscript.js

var category = null;
$("input[name='category']").click(function() {
    category = this.value;
    alert(category);
});

这行不通。

将deffer属性添加到脚本导入中。它将在所有浏览器都支持html后执行js
参考:http://www.w3schools.com/tags/att_script_defer.asp

或者,如果您正在使用jQuery,请确保所有处理程序都添加到onready函数中:

$(document).ready(function(){
var category = null;
$("input[name=category]").click(function() { // you don;t need quotes here for category name
    category = this.value;
    alert(category);
});
});

您可能需要在外部文件中添加jquery.load函数

$(window).load(function() {
    var category = null;
    $("input[name='category']").click(function() {
        category = this.value;
        alert(category);
    });
}

在关闭body标记之前,在html代码下导入js文件。然后运行

这应该可以完成您的工作:

$(document).ready(function(){
//Your code here....
});