在事件上删除并重新创建元素:

时间:2015-11-02 06:15:40

标签: javascript

我试图删除整个元素并在事件上重新创建它: 尽管有相同代码的几种变体,但我似乎无法做到这一点:

例如,对于事件,我需要删除元素,然后重新创建相同的元素。我不想删除文字:

这是我尝试过的(实验性的):结果不一致,代码重复。

function removeCreate(){

    var input = document.getElementById('display');
    var body = document.getElementsByTagName('body')[0];

    if(!!input){
        input.parentNode.removeChild(input);
        input = document.createElement('input');
        input.id = 'display';
        input.setAttribute('type',"text");
        body.appendChild(input);

    } else {
        input.parentNode.removeChild(input);
        input = document.createElement('input');
        input.id = 'display';
        input.setAttribute('type',"text");
        body.appendChild(input);
    }
}

1 个答案:

答案 0 :(得分:0)

您删除输入元素并重新创建输入元素的原因尚不清楚,但我们会说它会以某种方式进行修改,并且您希望重置"重置"它的州。

当你说'#34;我不想删除文字"时,我最明白的可能是你要保留用户输入的当前值。

如果这符合您的情况,那么您只需按住一个"模板"您的输入元素在内存中,以便您可以在需要时克隆它并使用克隆替换DOM中的克隆。执行此操作时,首先检索当前输入值,然后将其注入克隆输入。

结果:

var inputTemplate = document.createElement('input');
inputTemplate.setAttribute('type', 'text');

function cloneInput() {
    var newInput = inputTemplate.cloneNode(true);
    newInput.id = 'display';

    return newInput;
}

var input = document.getElementById('display');
var body = document.getElementsByTagName('body')[0];

if(!!input){
    // First retrieve the current value (what the user has typed / default value)
    var value = input.value;
    input.parentNode.removeChild(input);
    input = cloneInput();
    input.value = value; // Re-inject the value.
    body.appendChild(input); // Note that this would put your input at the bottom of the page.

} else {
    //input.parentNode.removeChild(input); // useless?
    input = cloneInput();
    body.appendChild(input);
}