jQuery函数在控制台中工作,但在代码中不起作用

Cra*_*aig 1 javascript jquery ready

下面的代码创建一个搜索字段,然后将焦点事件附加到它,以便当用户在输入字段中单击时预设值消失..focus行在控制台中工作,但不在代码中工作.如何让它在代码中工作?

<script type='text/javascript'>
jQuery( document ).ready(function( $ ) {
    jQuery('#site-nav').append("<div class='nav' style='width: 130px; margin-top: 15px;'><form     id='site-search' method='get' action='/search'><input id='search' name='search' class='textfield' tabindex='1' type='text' style='border-radius: 10px; height: 30px;' value='SEARCH'></form></div>")
});
jQuery("#search").focus(function(){$(this).val("");});
</script>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我必须拼出"jQuery",因为我们的应用程序配置为避免冲突的方式谢谢.祝福

Xav*_*ver 7

ready方法内移动线:

jQuery( document ).ready(function( $ ) {
    jQuery('#site-nav').append("<div class='nav' style='width: 130px; margin-top: 15px;'><form     id='site-search' method='get' action='/search'><input id='search' name='search' class='textfield' tabindex='1' type='text' style='border-radius: 10px; height: 30px;' value='SEARCH'></form></div>");
    jQuery("#search").focus(function(){$(this).val("");});
});
Run Code Online (Sandbox Code Playgroud)

编辑:

请记住,focus()如果字段获得焦点,则始终会触发匿名函数.因此在此操作后它将始终为空