繁体   English   中英

jQuery如果未选中单选按钮,则删除元素

[英]jQuery remove an element if radio button is not checked

我有以下代码,如果选中了相应的单选按钮,它们会将元素追加到文档中。 这可以正常工作,但是如果未选中单选按钮,我需要一种方法来删除元素。

到目前为止,这是我所拥有的?

// for each radio button
$('input[type=radio]').each(function(){ 

    // if it is checked
    if($(this).is(":checked")) 
        {
        var cur = $(this).val();
        // append an input text element only if it does not already exist
      if(!$('#characterList input:text').is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; }))
      {
        $('#characterList').append('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
      }
    }
   else
   {
    // otherwise remove element if radio button not checked
    $('#characterList').remove('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');   
   }

   });
 });

.remove(...)根本不执行任何操作。 我在这里做错了什么?

remove()不能那样工作。 您必须提供选择器以选择要删除的元素。 可以这样完成:

$('#characterList').remove('input[value="' + $(this).val() + '"]');

或者,或者:

$('#characterList').find('input[value="' + $(this).val() + '"]').remove();

此外, $(this).val()使用$(this).is(":checked")$(this).val() ,您还可以简单地使用:

if ( this.checked )

和:

var cur = this.value;

暂无
暂无

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

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