如何用JavaScript元素替换HTML元素或克隆它?

时间:2014-04-21 19:39:48

标签: javascript html replace textbox

如何用JavaScript元素替换HTML元素或克隆它(不删除HTML元素)? 我浪费了很多时间来尝试制作能够实现的JavaScript:

  1. 克隆HTML文本框/创建新的JS文本框

  2. 使用JS文本框替换HTML文本框,而不删除HTML文本框/在现有HTML文本框上放置HTML文本框的克隆。

  3. 我找不到解决方案。

    这是代码 - > 我在输出中得到[object HTMLInputElement] ...

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <html lang="en">
      <body>
      <td><input class="inputtext" name="first" id="first" tabindex="1" type="text"></td>
      <td><input class="inputtext" name="second" id="second" tabindex="1" type="text"></td>
    
      </body>
    </html>
    
      </body>
    </html>
    
    <script>
    function replaceTargetWith( targetID, html ){
      var i, div, elm, last, target = document.getElementById(targetID);
      div = document.createElement('div');
      div.innerHTML = html;
      i = div.childNodes.length;
      last = target;
      while(i--){
        target.parentNode.insertBefore((elm = div.childNodes[i]), last);
        last = elm;
      }
      /// remove the target.
      target.parentNode.removeChild(target);
    }
    </script>
    
    
    <script>
    
    
    var p = document.getElementById("first");
        var p_prime = first.cloneNode(true);
        p_prime.id = "first123"
        p_prime.name = "first123"
        p_prime.value = "testtest"
    
        document.getElementById("first").appendChild(p_prime)
    
    document.getElementById('first').value='emailtype@gmail.com' ;
    document.getElementById('second').value='LecimyTutaj' ;
    
    window.onload = function(){
      replaceTargetWith('first', document.getElementById('first123'));  
    }
    
    </script>
    

    我想隐藏新JavaScript创建的Textbox背后的现有HTML文本框,或者通过Javascript创建它而不删除它。 :)对不起,如果我写错了。

2 个答案:

答案 0 :(得分:0)

我不是在电脑上,所以很难添加代码示例来帮助你,但一般来说......制作一个HTML模型并在CSS中给它一个display:none(你不会使用它明确的块,所以不要在其中添加任何值...它只是在这里复制和粘贴)。给它一个像“myModel”的id。然后你可以在该模型上cloneNode(true)并根据你喜欢的时间添加它作为某个容器的子项。用您想要的任何值填充这些粘贴的实例。

如果没有人在接下来的几个小时内为您提供更多有用的帮助,我会在手机以外的地方添加代码示例。

答案 1 :(得分:-1)

我假设您想要动态添加更多输入字段。您将需要某种触发器,然后您可以使用JQuery的附加功能。

$("someBtnToTrigger").click(function(){
        $("#someForm > tbody:last").append("<td><input class='test123' name='test123'       
id='test123' tabindex='1' type='text'></td>");
        return false;