我试图使用动态选择单选按钮
$('#dashboard2 #dbMainPanel #bar2 #ddShowBar').attr('checked', true);
但是这个会导致form.reset()
失败。因为我在页面中有很多按钮,所以我在选择
$('#dashboard1 #dbMainPanel #bar1 #ddShowBar').attr('checked', true);
所有其他单选按钮都会重置。
如何避免这种情况?并保持页面中现有的单选按钮处于选中状态,然后动态更改当前单选按钮。
- 首先点击
div1
中的pie
- 然后点击
div2
中的bar
在这种情况下,我希望选择 div1
中的 pie
和 div2
中的 bar
最佳答案
您是否尝试过使用 .prop()
?
$('#ddShowBar').prop('checked', true);
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. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.
还有: in your example 您正在为您的 radio 组生成多个 ID
元素和重复的 attr: name。
每个新组的 radio 都需要一个与前一组不同的名称
。使用犁刀 c
变量很容易实现:
在此示例中,第一组中的 radio 将具有名称:txtradio0
;比下一组 radio :txtradio1
etc...
要保持其他行的 radio 被选中,您只需要更改组名称属性:
var r = ['Pie','Bar','Line','Area','Scatter'];
var c = 0; // a group counter // set to 1 if you want
function populateWithRadio(){
var rB = "<div class='radiobuttons'>";
for(var i=0; i< r.length; i++){ // create radios
rB += "<input type='radio' class='ddShow"+ r[i] +"' name='txtradio"+ c +"' value='"+r[i]+"'/>"+ r[i] ;
}
rB += "</div></br></br>";
c++; // increase Group counter
return rB; // returns the generated HTML to append
}
$('#div1').append( populateWithRadio() );
$('#div2').append( populateWithRadio() );
$(document).on("click", '.radiobuttons input', function () {
alert( 'CLASS: '+ this.className +'\n NAME: '+ this.name );
});
关于javascript - jquery 动态选择单选按钮(表单重置问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18212204/