2016-10-04 53 views
0

我试图做一个链接,当点击变成一个文本框。文本框在默认情况下是“关注”的,当你点击文本框外的任何地方时(这样就使它“不重点”,它会回到原来的链接。我试图在JQuery中使用replaceWith()函数来做到这一点,但不能正确地得到它的链接变成文本框,但但由于某种原因,我不正确理解它不会回到链接时,文本框是“未聚焦”。我已经创建说明这个小提琴。谁能告诉我什么,我做错了。replaceWith()在JQuery

,我用的是代码,

<script> 
    $(document).ready(function() { 
     $('a.edit').click(function() { 
     var removed = $(this).replaceWith("<input type='text' class='searchBox'/>"); 
     $('input.searchBox').focus(); 
     }); 

     $('input.searchBox').focusout(function() { 
     $(this).replaceWith('<a class="edit" href="#">Edit</a>'); 
     }); 
    }); 
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> 

<div class="controls"> 
    <a class="edit" href="#">Replace Link</a> 
</div> 

非常感谢。 :)

回答

1

将事件附加于母公司.controls元素,使用事件委派多的响应

$(document).ready(function() { 
 
    $(".controls").on("click", 'a.edit', function() { 
 
    var removed = $(this).replaceWith("<input type='text' class='searchBox'/>"); 
 
    $('input.searchBox').focus(); 
 
    }); 
 

 
    $(".controls").on("focusout", 'input.searchBox', function() { 
 
    $(this).replaceWith('<a class="edit" href="#">Edit</a>'); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> 
 
</script> 
 
<div class="controls"> 
 
    <a class="edit" href="#">Replace Link</a> 
 
</div>

+0

感谢。我仍然在学习JQuery,你的文章有很多帮助。 :) – Sudo

+0

@Sudu另请参见[为什么jQuery或诸如getElementById之类的DOM方法未找到该元素?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method -such-as-getelementbyid-not-the-element /),[Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – guest271314