我有一个选择标签,当它发生变化时,我会向用户显示另一个输入,当用户多次更改选择标签时,元素会在彼此之后插入,但我想在更改选择标签后删除旧输入,并且插入新的相关输入。
最佳答案
只需跟踪对元素的引用即可...
var element;
$("#sel").change(function () {
var sel = $(this);
if(element)//check if an input has already been created
element.remove();//remove the old input from the DOM
element = $("<input/>").val(sel.val());//create the new input and store the reference
element.insertAfter(sel);//insert the new input to the DOM
});
$("#sel").change();
因为 insertAfter
是您正在创建的元素的函数,所以您必须已经在当前代码中创建了对它的引用。因此,您只需全局存储该引用即可。然后每次更改选择时,您都可以检查引用是否有值并将其从 DOM 中删除。
关于javascript - 如何访问使用 jquery insertAfter 方法创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17974289/