2015-11-03 66 views
1

我跟着这个例子来捕获的onChange()jQuery的事件单选按钮组: JQuery $(#radioButton).change(...) not firing during de-selectionjQuery的单选按钮平变化不工作

但在我的情况下,在该例子中给出的解决方案是行不通的。我有以下从我的JSP生成:

<input id="object.reportEntity.reportEntityIsPrime1" name="object.reportEntity.reportEntityIsPrime" type="radio" value="Y_YES" checked="checked"/>Prime        

<input id="object.reportEntity.reportEntityIsPrime2" name="object.reportEntity.reportEntityIsPrime" type="radio" value="N_NO"/>Not Prime 

JS:

$(document).ready(function() {  

    // Display Alert on Radio Change  
    $('input[name=object.reportEntity.reportEntityIsPrime]:radio').change(function() { 
     alert('Radio Button clicked'); 
    }); 
} 

警报没有被diplayed。此外,还有这样的错误:

语法错误,无法识别的表达式“输入”

+0

这是JSP错误还是JS错误? –

+0

JavaScript(JS)错误。我怀疑这是因为名称中使用的点。 –

+0

为什么你有这么长的id名字?我认为这是C# –

回答

1

使用引号你的名字是这样的:

$('input[name="object.reportEntity.reportEntityIsPrime"]:radio') 
4

您应该委托的事件。

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

此外,您需要在您的选择器中添加"[name=""]遵守以下...

$('body').on('change', 'input[name="object.reportEntity.reportEntityIsPrime"]:radio', function() { 
    alert('Radio Button clicked'); 
}); 
  • 侧面说明:你在你的ready函数的末尾缺少);

JSFiddle Link - 工作演示

此外,要务必查看jQuery Understanding Event Delegation docs以获取更多信息

1

报价在您选择的字符串中的name属性。

$(document).ready(function() {  

      // Display Alert on Radio Change  
    $('input[name="object.reportEntity.reportEntityIsPrime"]:radio').change(function() { 
       alert('Radio Button clicked'); 
      }); 

    }