无线电输入控制与外部按钮

Radio Input Control with External Button

本文关键字:外部 按钮 控制 输入 无线电      更新时间:2023-09-26

你好,我正在制作一个单选输入的幻灯片,并设计了" previous "answers"next"按钮来移动幻灯片。但是,我还希望按钮也检查下一个输入。当前幻灯片移动,但未检查下一个输入。我在这里看到了这个解决方案:选择带有外部按钮的下一个/上一个单选按钮并试图实施它,但我不能让它工作。下面是我的代码:

<form action="" method="post">
    <ul class="form-ul" style="position: relative; width: 176px; height: 107px;">                            
      <li style="position: absolute; top: 0px; left: 0px; display: block; z-index: 5; opacity: 1; width: 82px; height: 43px;">
        <label>
          <input type="radio" name="term_id" value="59" checked="checked">
        </label>
      </li>
      <li style="position: absolute; top: 0px; left: 0px; display: none; z-index: 4; opacity: 0; width: 82px; height: 62px;">
        <label>
          <input type="radio" name="term_id" value="61">
        </label>
      </li>
    </ul>
    <div id="prev" style="float:left;">PREV</div> 
    <div id="next" style="float:right;">NEXT</div>
</form>
JavaScript:

$(document).ready(function(){
  $('#prev').click(function(){
    $('.form-ul').find('li:has(input:checked)').prev().children('input').prop("checked", true);
  });
  $('#next').click(function(){
    $('.form-ul').find('li:has(input:checked)').next().children('input').prop("checked", true);
  });
});

jQuery的.children()只查找元素的直接子元素。在您的示例中,单选按钮不是直接子按钮,因此您需要将其更改为.find():

$(document).ready(function(){
  $('#prev').click(function(){
      $('.form-ul').find('li:has(input:checked)').prev().find('input').prop("checked", true);
  });
  $('#next').click(function(){
      $('.form-ul').find('li:has(input:checked)').next().find('input').prop("checked", true);
  });
});

还可以通过减少查询来提高性能。而不是

$('.form-ul).find('li:has(input:checked)')
使用

$('.form-ul li:has(input:checked)')

要使其循环,请检查结果集的length:

$('#next').click(function(){
  var $next = $('.form-ul li:has(input:checked)').next();
  if(!$next.length) $next = $('.form-ul li').first();
  $next.find('input').prop("checked", true);
});

这是小提琴和圆形小提琴