我有以下 HTML 和 Javascript 代码。我正在尝试制作一个搜索建议系统。当用户在输入框“site_search”中键入并插入时,使用ajax动态检索无序列表“search_suggest”中的列表项。
<form name="search_site_form" method="get" action="search.php">
<input id="site_search" name="q" class="search_input input" autocomplete="off" value="Search the site" type="text"/>
<ul id="search_suggest">
</ul>
<input value=" " type="submit" class="search_submit"/>
<script type="text/javascript">
<!--
$("ul#search_suggest>li").click(function(){
alert('123');
});
//-->
</script>
</form>
但是,单击 search_suggest 中的列表项不会触发单击功能。知道为什么吗?
最佳答案
在将列表项添加到页面后,您需要将单击事件绑定(bind)到列表项。
在将任何列表项添加到页面之前,表达式 $("ul#search_suggest>li")
找不到任何内容,因此没有元素绑定(bind)到单击事件。
您需要使用.live
这将:
Attach a handler to the event for all elements which match the current selector, now and in the future
如下所示:
<script type="text/javascript">
<!--
$("ul#search_suggest>li").live('click', function(){
alert('123');
});
//-->
关于javascript - jquery .click 函数没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4571064/