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

用户名

这段代码可以正常工作

的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>

脚本

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);
});
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章