jQuery不会触发单选按钮更改 [英] jQuery not triggering on radio button change
问题描述
很抱歉打扰,但我是jquery的新手并试图解决这个问题。谢谢你提前。
Sorry for bothering, but I'm new to jquery and trying to figure this out. Thanks in advanced.
我有一个网页,里面有几组基于几个计算机组件的单选按钮。我的页面顶部有一些图像可以触发某些单选按钮。我对此的javascript是:
I have a web page filled with several sets of radio buttons based on several computer components. I have some images at the top of my page that trigger certain radio buttons to be pushed. The javascript I have for this is:
$( document ).ready( function() {
$('img#gaming').click(function () {
$('.small_image').attr("src","../img/GamingPlain.png");
$('input:radio[name=chasis]')[2].checked = true;
$('input:radio[name=cpu]')[1].checked = true;
$('input:radio[name=mobo]')[1].checked = true;
$('input:radio[name=ram]')[1].checked = true;
$('input:radio[name=gpu]')[1].checked = true;
$('input:radio[name=psu]')[1].checked = true;
$('input:radio[name=hdd]')[2].checked = true;
});
.
.
.
});
这是正常的。我还必须根据选择的单选按钮更改页面的一部分。它看起来像这样:
This works correctly. I also have to change a portion of the page based on which radio button is selected. It looks like this:
$( document ).ready( function() {
$('input[name=chasis]').change(function() {
var txt = $(this).parent().text();
var price = txt.match(/(\$)([\d]+)/)
$('span#chasisprice').text(price[0]);
});
$('input[name=cpu]').change(function() {
var txt = $(this).parent().text();
var price = txt.match(/(\$)([0-9]+)/)
$('span#cpuprice').text(price[0]);
});
.
.
.
});
这也正常。但是,当我使用第一段代码(用户点击'img#gaming')选择自动选择单个单选按钮时,第二段代码不会触发(也就是未注册更改)。
This also works correctly. However, when I use the first piece of code (a user click on 'img#gaming') to select the automatically select the individual radio buttons, the second piece of code does not trigger (aka a change is not registered).
是否有不同形式的.change将注册新选择的单选按钮?或者选择用于注册更改的单选按钮的不同方式?
Is there a different form of .change that will register the new selected radio buttons? or a different way of selecting the radio button that would register the change?
推荐答案
您可以使用<$ c触发更改事件$ c> .trigger():
...
$('input:radio[name=psu]')[1].checked = true;
$('input:radio[name=hdd]')[2].checked = true;
$('input:radio').trigger('change');
此外,请勿使用输入:radio
。 input:radio
不是CSS选择器, document.querySelector
不支持,因此它将运行慢于输入[type =radio]
。
Also, don't use input:radio
. input:radio
isn't a CSS selector and won't be supported by document.querySelector
, so it will run slower than input[type="radio"]
.
我建议你重新考虑你的布局。您不必每次只需稍作更改就重复相同的代码块。
I suggest you re-think your layout. You should't have to repeat the same block of code every time with just minor changes.
这篇关于jQuery不会触发单选按钮更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!