简体   繁体   English

javascript jquery选择单选按钮

[英]javascript jquery selecting radio buttons

I have a php script that outputs many divs, in each div is a radio button with a specific value. 我有一个输出许多div的php脚本,每个div中都有一个具有特定值的单选按钮。 I want to create a better user experience by having the radio button selected when the div is clicked, which isn't much of a problem when I use jquery. 我想通过单击div时选择单选按钮来创建更好的用户体验,当我使用jquery时这不是什么大问题。 The problem is, when the radio button itself is clicked and not the div, the following clicks don't have the effect of selecting the radio button any more. 问题是,当单击单选按钮本身而不是div时,以下单击不再具有选择单选按钮的效果。 I also tried to remove the checked attribute on every radio button before checking the selected one, but this doesn't work. 我还尝试在选中所选单选按钮之前删除每个单选按钮上的checked属性,但这不起作用。 Here is how I do it: 这是我的方法:

$(".fontCellDiv").click(function(){ 
     $(this).find("input").attr("checked", true);
 });

Has anyone an idea? 有人知道吗?

Use .prop() instead of .attr() 使用.prop()而不是.attr()

From the documentation: 从文档中:

Attributes vs. Properties 属性与属性

The difference between attributes and properties can be important in specific situations. 属性和属性之间的差异在特定情况下可能很重要。 Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. 在jQuery 1.6之前,.attr()方法在检索某些属性时有时会考虑属性值,这可能会导致行为不一致。 As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. 从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。

 $(".fontCellDiv").click(function(){ $(".fontCellDiv").find("input").removeAttr('checked'); $(this).find("input").attr("checked", true); }); 
 .fontCellDiv{ width: 100px; background-color: #0f0; margin-bottom: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> 

Check this sample. 检查此样本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM