如何移除动态输入框场景下join()方法添加的分隔符?
问题:动态输入框对应内容的分隔符同步移除问题
我想要实现类似某Vue.js站点的效果,但需要用jQuery/JavaScript方案。目前已实现以下功能:
- 输入事件触发时,将所有带
.custom类的输入框值转为带<span>标签的元素数组,用|分隔后显示在#token容器中 - 通过「添加/移除」按钮动态增删带特定ID的输入框
遇到的问题:使用join()添加的|分隔符,在删除输入框及对应内容后会残留,无法同步移除。
初始代码
HTML
<body> <div class="container"> <div class="wrapper"> <article> <section> <div class="flex-row"> <label for="custom_text_one"><input id="custom_text_1" class="custom" type="text" name="" placeholder="custom text"></label> <button class="remove">-</button> </div> <div class="flex-row"> <label for="custom_text_two"><input id="custom_text_2" class="custom" type="text" name="" placeholder="custom text 2"></label> <button class="remove">-</button> </div> <button class="add">+</button> <div class="flex-row"> <div>customText{{[<span id="token"></span>]}}</div> </div> </section> </article> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </body>
JavaScript
$('body').on('input', '.custom', function(event) { var tokens=''; var i = 0; var token = $('.custom').map(function() { i++; return '<span id="custom-'+ i +'">' + this.value + '</span>'; }).get().join('|'); tokens += token; $('#token').html(tokens); //remove related input value in the result div $('.remove').click(function(){ $('#custom-'+ i +'').remove(); i--; }); }); // 初始已有两个输入框,新增输入框ID从3开始 var count = 3; $('.add').click(function() { var y = '<div class="flex-row"><label><input id="custom_text_' + (count++) + '" class="custom" type="text" name="" placeholder="custom text"></label><button class="remove">-</button>'; $(y).insertBefore('.add'); }); $('body').on('click','.remove', function(){ $(this).parent('.flex-row').remove(); }) });
解决后最终代码
感谢帮助,已添加移除功能,现在可同步删除输入框与对应输出内容,最终代码如下:
$("#inputs").on('input', 'input[type=text]', function(event) { var i = $(this).closest(".flex-row").index(); var v = (i == 0) ? $(this).val() : "|" + $(this).val(); $("#custom_wrapper .output").eq(i).html(v); }); $('.add').click(function() { var count = $("#inputs input").length; count++; var row = $("<div>", { class: "flex-row" }).insertBefore(this); $("<label>").appendTo(row); $("<input>", { type: "text", class: "input", placeholder: "custom text " + count, id:"custom-text-" +count, tabindex: count }).appendTo($("label", row)); $("<button>", { class: "remove" }).html("-").appendTo(row); $("<span>", { class: "output", dataid:"custom-text-" +count, }).insertAfter($("#custom_wrapper .output:last")); }); $('body').on('click','.remove', function(){ $(this).parent('.flex-row').remove(); var j =$(this).parent().find('.input').attr("id"); $('#custom_wrapper .output[dataid="'+ j +'"]').empty(); })
内容的提问来源于stack exchange,提问作者blogob
相关产品推荐
相关产品推荐

