2015-09-07 75 views
0

我想切换文本框使用下面的代码,但它似乎不工作。我能够添加文本框,但删除没有发生。Jquery切换文本框

HTML:

<body id="bd"> 
    <div id="did"></div> 
    <button id="btn" >Tryit</button> 
</body> 

JS:

$(document).ready(function(){ 
    $("#btn").click(function(){ 
     $("#bd").append('<input type="Text" name="fname" id="fname" />'); 
     $("#fname").focus(); 
     $("#btn").attr("id","button"); 
    }); 
    $("#button").on("click",function(){ 
     $("#fname").remove(); 
     $("#button").attr("id","btn"); 
    }); 
}); 
+0

如果要动态地添加元素的尝试使用委托()函数 –

回答

0

试试这个切换:

 $(document).ready(function(){ 
      $("#btn").on('click',function(){ 

       if($("#fname").length > 0){ 
        $("#fname").remove(); 
       }else{ 

        $("#bd").append('<input type="Text" name="fname" id="fname" />'); 
        $("#fname").focus(); 
        $("#btn").attr("id","button"); 

       } 

      }); 

     }); 
    </script> 
</head> 
<body id="bd"> 
<div id="did"></div> 
<button id="btn" >Tryit</button> 
</body> 
</html> 
+0

Thanks.Its working.but但我不能标记此为答我是这个网站的新手。 – Verma

+0

你可以从这里阅读。 http://meta.stackexchange.com/a/147532谢谢 – guvenckardas

+0

这是明确的帖子,我发送给你吗?谢谢 – guvenckardas

0

请试试这个:

$(document).delegate("#btn", "click", function() { 
    $("#bd").append('<input type="Text" name="fname" id="fname" />'); 
    $("#fname").focus(); 
    $("#btn").attr("id","button"); 
}); 
$(document).delegate("#button", "click", function() { 
    $("#fname").remove(); 
    $("#button").attr("id","btn"); 
}); 

DEMO

可以使用delegate用于动态创建的元素附加事件。

0

您需要使用:

$("#btn").on('click',function(){ 
    if($("#fname").length) 
    $("#fname").remove(); 
    else{ 
    $("#bd").append('<input type="Text" name="fname" id="fname" />'); 
    $("#fname").focus(); 
}}); 
0

尝试委托click事件document,利用.replaceWith()

<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
 
    <script> 
 
    $(document).ready(function() { 
 

 
     var fn = function fn() { 
 
     $("#bd").append('<input type="Text" name="fname" id="fname" />'); 
 
     $("#fname").focus(); 
 
     $(this).replaceWith($("<button id=button>Try it</button>")); 
 
     }; 
 

 
     $(document).on("click", "#btn", fn); 
 

 
     $(document).on("click", "#button", function() { 
 
     $("#fname").remove(); 
 
     $(this).replaceWith($("<button id=btn>Try it</button>")).click(fn); 
 
     }); 
 

 
    }); 
 
    </script> 
 
</head> 
 

 
<body id="bd"> 
 
    <div id="did"></div> 
 
    <button id="btn">Tryit</button> 
 
</body> 
 

 
</html>