单击整个父级的任意点时更改单选按钮输入 div

Change radio button input when click on the any point of the entire parent div

我正在使用无线电输入作为切换要在我的网站上显示的语言的开关。无线电输入有一个 class 的“.switch”,它被其父 div “.switch-block”包裹。我想实现的是,当点击parentdiv(.switch-block,下面jsfiddle上的彩色部分)的任意一点时,输入状态也会改变。

我的 jquery 代码不起作用:

$('.switch-block').click(function(){
     $( ".switch" ).change();
});

这是我对 jsfiddle 的尝试: https://jsfiddle.net/9ev9s6h2/

$('.switch-block').click(function(){
     if($( ".switch" ).attr("checked"))
        $( ".switch" ).attr('checked', true);
     else
        $( ".switch" ).attr('checked', false);
});

做这样的事情。

 $('.switch-block').click(function (e) {
     var $target = $(e.target);
     if (!($target.is(':radio'))) {
         $(this).find('input:radio:NOT(:checked)').prop('checked', true)
     }
 });

你可以试试这个。

  1. 将点击事件附加到容器。
  2. 抓住目标,如果目标是收音机,那么你只需执行默认操作。
  3. 如果目标元素不是收音机,则将未选中的收音机的属性更改为 checked = true。

https://jsfiddle.net/usq5gb96/

根据您的 html 此代码有效:

$('.switch-block').click(function(){
    $fr=$("#switch-fr");
    $en=$("#switch-en");
     if($en.is(":checked")) {
        $en.prop('checked', true);
     } else if($fr.is(":checked")) {
        $fr.prop('checked', true);
     }
   console.log($(this).find("input:radio:checked").val());
});

正如您在 console.log 中看到的那样,它选择了正确的语言选项 这里是工作 fiddle