2015-12-24 134 views
0

我读了很多关于计算器的事情,但没有帮助我:(如何检测这个单选按钮是否被选中?

我有这样的HTML表格,通过Ajax请求加载:

<table class="table table-striped table-hover choix_annonce_table"> 
    <thead> 
     <tr> 
      <th>Sélection</th> 
      <th>Visuel</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td><input type="radio" value="45" name="idAnnonce"></td> 
      <td><img alt="Annonce 1" src=""></td> 
     </tr> 
     <tr> 
      <td><input type="radio" value="46" name="idAnnonce"></td> 
      <td><img alt="Annonce 2" src=""></td> 
     </tr>   
    </tbody> 
</table> 

我尝试当单选按钮被选中来检测,但没有以下问题的工作(在js文件包括在我的 “主” 页):

$(document).ready(function() { 
    $("input[name=idAnnonce]").click(function(){ 
     alert("xx"); 
    }); 
}); 

OR

$(document).ready(function() { 
    $("input[name=idAnnonce]:radio").change(function() { 
     alert("xx"); 
    }); 
}); 

你有想法吗?

编辑:当我加载JS直接到我的加载表与Ajax,它的工作原理。 为什么?

+0

的可能的复制【使用方法上的改变事件无线电?(http://stackoverflow.com/questions/13152927/how-to-use-radio -on-change-event) – robbmj

+0

阅读选中的属性? 'console.log(this.checked);' – epascarello

+1

[Find out if if radio button is checked with JQuery?](http://stackoverflow.com/questions/2272507/find-out-if-radio-button-使用jquery进行检查) – Heroselohim

回答

1

如果你的javascript被直接加载到html文件中,那么当html文件被加载和解析时,它会被一行执行。当javascript在一个单独的文件中时,它需要被调用。你可以通过执行一个“onload”函数作为你的body标签语句的一部分。你的html的那部分缺失,所以目前还不清楚你的表是否真的在加载时加载任何东西。
您也可以在ajax加载结束时通过回调执行这些事件监视器。

3

这是因为.click().change()方法,与其他所有事件处理一起,只为观看上的元素,这些事件是在事件被附着时间目前

为了解决这个问题,而不是使用这样的:

$('input[name=idAnnonce]').change(function() { 
    // ... 
}); 

使用这样的事情,而不是:

/* Use 'body' or any element that will contain the form */ 
$('body').on('change', 'input[name=idAnnonce]', function() { 
    // ... 
}); 

这将观看传递到身体的点击事件,只调用函数为那些匹配选择器。

+0

好的答案,但是您应该使用radio上的'change'事件和复选框输入,以便在通过键盘更改选择时还会触发事件。 –

+0

@RoryMcCrossan我补充说。谢谢! –

+0

不,它不工作:( 我已经将您的方法添加到我的全局js文件中,并且没有任何情况发生 – bahamut100

1

当通过ajax加载表时,您需要通过ajax调用来引入javascript。这意味着进来的表还应该包含引用表的JavaScript。父页面上的DOM不知道表,所以父页面上的JavaScript不会对新内容起作用。

0
$(document).ready(function() { 
    $('input[type=radio][name=idAnnounce]').change(function(evt) { 
    console.log(evt.target.value) 
    }); 
}); 

您使用的选择器是错误的。

上面的代码应该帮助

欢呼

相关问题