gpt4 book ai didi

javascript - 单击时从输入中删除字符串?查询

转载 作者:行者123 更新时间:2023-11-29 17:16:10 24 4
gpt4 key购买 nike

我正在尝试编写自己的函数来将标签中用逗号分隔的每个字符串包装起来,我有这个工作,但是在“关闭”点击 id 时喜欢从输入中删除相应的字符串,这可能吗有没有?

jQuery

$('body').on('click', '.tag span', function(){ 
$(this).parent().hide();
});
$('input').keyup(function(e) {
$('.result').html('');
var valueArr = $(this).val().split(',');
for(var i=0; i<valueArr.length; i++){$('.result').append('<div class="tag">'+valueArr[i]+'<span> X</span></div>')};
});

http://jsfiddle.net/Liamatvenn/7huQ4/1/

最佳答案

试试这个:

$('body').on('click', '.tag span', function(){ 
$(this).parent().hide();
$(this).closest('.result').prev('input').val(""); //get the input respective to the clicked close button.
});

.closest() 会将您带到父级 .result 并仅针对其之前使用 生成标签的 input .prev().

Demo

更简单的是,使用被点击的标签元素的索引,并根据它们按顺序插入的相同索引从数组中删除相应的元素。

$('body').on('click', '.tag span', function () {
var $parent = $(this).closest('.tag');
var index = $parent.index(); //Get the index of the `tag`

$(this).closest('.result').prev('input').val(function (_, value) { //use val function argument
var values = value.split(','); //split the value
values.splice(index, 1); //remove the item from array
return values.join(','); //join them back
});

$parent.remove(); //then remove your tag
});

Demo

关于javascript - 单击时从输入中删除字符串?查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578122/

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