2013-07-31 81 views
1

我有一个select标签,当它发生更改时,我向用户显示另一个输入,并且当用户更改select标签多次时,元素之间会插入另一个元素,但是我想在更改选择标记并插入新的相关输入后删除旧的输入。如何访问使用jquery insertAfter方法创建的元素

+0

今后,请提供您的现有代码的一个相关的例子。事实上,编辑它到这个不会有什么伤害。 – musefan

回答

1

只要保持那么元素的引用的轨迹......

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(); 

Here is a working example

因为insertAfter是要创建,你必须已经创建对它的引用的元件的功能无论如何,在你当前的代码中。所以你只需要在全球范围内存储该参考。然后,每次更改选择时,都可以检查引用是否有值,并将其从DOM中删除。

0

创建新的元素之前将新元素的可选divspan,并清空容器:

$('#inputContainer').empty().append('<input/>');