简体   繁体   English

使用 jQuery 检查单选按钮不会触发单选按钮的 onclick 事件

[英]Checking radio button with jQuery doesn't trigger radio's onclick event

I have a pair of radios, to which I assign a function using bind(), on the pages.ready event.我有一对收音机,我在 pages.ready 事件上使用 bind() 为其分配了一个函数。 then, on the same ready event, I check for another input's value, and if it's value is "1" I preselect the second radio button when the page loads.然后,在同一个就绪事件中,我检查另一个输入的值,如果它的值为“1”,我在页面加载时预选第二个单选按钮。 here is a snippet.这是一个片段。

<input type="radio" name="fpago" id="fpago1" value="1" />one
<input type="radio" name="fpago" id="fpago2" value="2" />two

... ...

$(document).ready(function() {
    $("#myspan").hide();

    $("#fpago1, #fpago2").bind('change click',function(){
        togglePlazo();
    });

//initial condition to preselect radio #2
    grupo = $("#id_grupo").val();
    if(grupo != '0'){
        $("#fpago2").attr('checked', true); //checks the radio, but doesn't trigger function
    }

});

... ...

--> see here for a more complete code --> 更完整的代码见这里

The problem is that, the radio does get checked if the condition is met, BUT the bound function togglePlazo() doesn't trigger...问题是,如果满足条件,无线电会得到检查,但绑定函数togglePlazo()不会触发......

If later I manually click the radio buttons, the function does get triggered, and the span toggles.如果稍后我手动单击单选按钮,该功能会被触发,跨度也会切换。 It is only on the initial "check" made with jQuery, where the function does not trigger despite the radio getting changed.它只是在使用 jQuery 进行的初始“检查”时,尽管无线电已更改,但该功能不会触发。

I don't know what I'm missing, maybe I should bind more events other than change or click... I just can't find what I am doing wrong.我不知道我错过了什么,也许我应该绑定更多事件而不是更改或单击......我只是找不到我做错了什么。

NOTE: I am using jQuery 1.4.2, but the fiddle is set to use 1.6.4 (it doesn't have 1.4.2 as an option)注意:我使用的是 jQuery 1.4.2,但小提琴设置为使用 1.6.4(它没有 1.4.2 作为选项)

Just trigger the click event when you set the checked attribute. 只需在设置checked属性时触发click事件。

$("#fpago2").attr('checked', true).trigger('click');

Changing an attribute on the element doesn't fire a changed event... Neither by the native setAttribute or using jQuery's attr. 更改元素上的属性不会触发已更改的事件...既不是本机setAttribute也不是使用jQuery的attr。

If you write console.log('yes');如果你写console.log('yes'); inside imageTypeToggle function and you will see on page load in console yes will not print.imageTypeToggle函数中,您将在控制台的页面加载中看到yes不会打印。 you need to trigger like below你需要像下面这样触发

$(function () {
    $(window).load(function(){
    $("[name=image_type]").on("change",imageTypeToggle).trigger('click');
 })

$('input:radio[name="fpago"]').filter( [value="1"] ).prop('checked', true).trigger("change"); $('input:radio[name="fpago"]').filter( [value="1"] ).prop('checked', true).trigger("change");

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

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