gpt4 book ai didi

javascript - 能够在单击时添加选项但无法将其删除(切换)

转载 作者:行者123 更新时间:2023-12-03 08:31:06 29 4
gpt4 key购买 nike

我尝试在单击切换时将选项添加到选择菜单,但如果再次单击(取消选择),则可以将其删除。到目前为止,我可以在单击时向选择菜单添加单个值,但无法将其删除(切换添加切换删除)

这是我的代码:

HTML

<div class="listview lv-user m-t-20">
<div class="lv-item media">
<div class="lv-title">this is test 1</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 1">
</div>
</div>
<div class="lv-item media">
<div class="lv-title">this is test 2</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 2">
</div>
</div>
<div class="lv-item media">
<div class="lv-title">this is test 3</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 3">
</div>
</div>


Jquery

$(".lv-item").on("click", function(){
alert($(this).find('#screen_name_test').val());
$(this).toggleClass("active");
$(this).find('#account_selected').toggle();
$('#mySelect').append($('<option>', {
value: $(this).find('#social_media_test').val(),
text: $(this).find('#screen_name_test').val()
}).attr('selected',true)
);
});

if($(".lv-item").not('active'))
{
$('#mySelect').remove($('<option>', {
value: $(this).find('#social_media_test').val(),
text: $(this).find('#screen_name_test').val()
}).attr('selected',false)
);
}

我还创建了一个JsFiddle

最佳答案

我有一些不同的方法,但它非常简单。请看一下,如果对您有帮助,请告诉我。

Working:Example

HTML

<div class="listview lv-user m-t-20">
<div class="lv-item media">
<div class="lv-title">this is test 1</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 1">
</div>
</div>
<div class="lv-item media">
<div class="lv-title">this is test 2</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 2">
</div>
</div>
<div class="lv-item media">
<div class="lv-title">this is test 3</div>
<input type="hidden" name="screen_name_test" id="screen_name_test" value="this is test 3">
</div>
</div>
</div>
<br>
<select id="mySelect" name="mySelect[]" multiple></select>

JavaScript/JQuery

$(".lv-item").on("click", function () {
alert($(this).find('#screen_name_test').val());
var curOption = $(this).find('#screen_name_test').val();

var sts = $('#mySelect').find('option[value="' + curOption + '"]').length;
if (sts == false) {
$('#mySelect').append('<option value="' + curOption + '" selected>' + curOption + '</option>');
} else {
$('#mySelect').find('option[value="' + curOption + '"]').remove();
}

});

关于javascript - 能够在单击时添加选项但无法将其删除(切换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326809/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com