单击单选按钮时,将值附加到 div 并在单击另一个单选按钮时从 div 中删除

基本上,我试图在单击时将单选按钮值附加到 div。这可以正常工作,但是当单击另一个单选按钮时我似乎无法清除 div。


div 中只能有 1 条附加数据。


我尝试在附加值之前使用innerHTML清除div,但似乎不起作用


$('input[type="radio"]').one('click', function () {


  var getVal = $(this).val();


  if ($('.selections').text().length < 0) {

    console.log('less than');

  } 

  else if ($('.selections').text().length > 0){

    console.log('more than');

    $('.selections').innerHTML = "";

    $('.selections').append(getVal);

  }


  console.log(getVal);

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>

  <label>


    <span class="radio-c">

      <input type="radio" name="q1" value="Between £381K and £450K" id="between381">

      Between £381K and £450K

    </span>

  </label>

  <label>

    <span class="radio-c">

      <input type="radio" name="q1" value="Over £450K" id="over450">

      Over £450K

    </span>

  </label>

</form>



<div class="selections">


</div>


一只名叫tom的猫
浏览 128回答 1
1回答

翻翻过去那场雪

innerHTML使用 vanilla JS 时使用。您应该在 jQuery 引用的对象上使用text()。您也不需要在此处附加。我也相信你用错了.one(),应该是的.on()。$('input[type="radio"]').on('click', function () {&nbsp; var getVal = $(this).val();&nbsp; if ($('.selections').text().length < 0) {&nbsp; &nbsp; //console.log('less than');&nbsp; } else if ($('.selections').text().length > 0){&nbsp; &nbsp; //console.log('more than');&nbsp; &nbsp; $('.selections').text(getVal);&nbsp; }&nbsp; //console.log(getVal);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form>&nbsp; <label>&nbsp; &nbsp; <span class="radio-c">&nbsp; &nbsp; &nbsp; <input type="radio" name="q1" value="Between £381K and £450K" id="between381">&nbsp; &nbsp; &nbsp; Between £381K and £450K&nbsp; &nbsp; </span>&nbsp; </label>&nbsp; <label>&nbsp; &nbsp; <span class="radio-c">&nbsp; &nbsp; &nbsp; <input type="radio" name="q1" value="Over £450K" id="over450">&nbsp; &nbsp; &nbsp; Over £450K&nbsp; &nbsp; </span>&nbsp; </label></form><div class="selections"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript