在外部.js文件中使用jQuery来处理单击单选按钮

时间:2013-06-16 21:05:16

标签: javascript jquery radio-button

我在Debian 7.0.0上使用jQuery 2.0.2。

我已经设置了一组单选按钮。

<table border="1">
<tr>
<th align="center" colspan="2" style="background:orange">Look Up Table</th>
</tr>
<tr align="left">
<td><input type="radio" name="LUT" id="GREY" value="GREY" onclick="EnableNonlinear()" 
    <?php echo $greyLUT ?>/>Gray</td>
<td><input type="radio" name="LUT" id="HOS" value="HOS" onclick="EnableNonlinear()"  
    <?php echo $hosLUT ?>/>Heated Object</td>
</tr>
</table>

如果我用

跟随这段代码
<script type="text/javascript">
jQuery('input[name=LUT]').change(function(){
alert('Radio button clicked');
});
</script>

单击其中一个单选按钮时会出现警告框。但是,如果我使用

<script type="text/javascript" src="DisplayOrAnalyzeSingleArray.js"></script>

并放

jQuery('input[name=LUT]').change(function(){
alert('Radio button clicked');
});

在DisplayOrAnalyzeSingleArray.js中,当我点击其中一个单选按钮时没有任何反应。我这样做,但是当我加载

时,当加载页面时会出现警告框
alert('Radio button clicked');

在DisplayOrAnalyzeSingleArray.js。

我很困惑为什么单个alert语句在外部文件中工作,如果我将它放在html代码中,jQuery事件处理程序可以工作,但如果我将它放在外部文件中,则事件处理程序不起作用。 / p>

我在Ice Weasel 10.0.12上使用Firebug 1.7.3但控制台上没有出现任何错误消息。

2 个答案:

答案 0 :(得分:4)

首先确保在jquery之后包含你的脚本 -

<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="DisplayOrAnalyzeSingleArray.js"></script>

并将代码包装在.ready处理程序

jQuery(function(){
  jQuery('input[name=LUT]').change(function(){
    alert('Radio button clicked');
  });
});

答案 1 :(得分:2)

我认为你的代码必须是我,

 $(document).ready( function({
    jQuery('input[name=LUT]').change(function(){
    alert('Radio button clicked');
    });
 });

因为,您的代码可能在包含.js文件之前执行。为确保您的代码仅在加载了所有.js文件后才能执行,您可以在.onready()函数中包含您的实际javascript代码。