php - Jquery 单击在下拉菜单上不起作用

标签 php jquery onclick

我有一个类似于 Google 的搜索,当用户键入时会下拉显示结果。理想情况下,我希望用户单击这些结果之一,该值就会进入搜索框。但是,当我点击结果时,什么也没有发生。

HTML:

<input type='text' id='topicInput' name='topic' autocomplete='off' />
<div id='tagResult'></div>  //this is the dropdown

JQUERY:

$('#topicInput').keyup(function(){

        var topic = $(this).val();
        if (topic==''){
            $('#tagResult').css("display" , "none");
        }
        else{
            //$('div').click(function(){
                //$('#tagResult').css("display" , "none");

            //});
            $('#tagResult').css("display" , "block");

                $.post('../topic.php' , {topic: topic} , function(response){

                $('#tagResult').html(response);     
                });
            }
    });
     //the above code is working properly

$('.topicResult').click(function(){
    alert(1);   //this is just a test, but it never shows up
});

所以,当我点击 .topicResult 时什么也没有发生。应该会出现一个警报。我已经验证 topic.php 实际上确实返回带有 topicResult 类的 div。

最佳答案

您正在绑定(bind)单击事件,然后在绑定(bind)监听器后将元素添加到页面。它不会着火。

两个选项

选项 1,使用可以在页面呈现后绑定(bind)到元素的监听器

对于 jQuery 1.7+,可以更改 .topicResult 的点击事件以使用“.on()”,或者对于以前的版本使用“.live() 或 .delegate()”

 $(document).on('click','.topicResult',function(){
      alert('1');
 )};

选项 2,移动您的点击绑定(bind),以便在添加元素后将其绑定(bind)

 $('#topicInput').keyup(function(){ 

    var topic = $(this).val(); 
    if (topic==''){ 
        $('#tagResult').css("display" , "none"); 
    } 
    else{ 
        //$('div').click(function(){ 
            //$('#tagResult').css("display" , "none"); 

        //}); 
        $('#tagResult').css("display" , "block"); 

            $.post('../topic.php' , {topic: topic} , function(response){ 

            $('#tagResult').html(response);
                $('.topicResult').click(function(){ 
                      alert(1);   //this is just a test, but it never shows up 
                 }); 

            }); 
        } 
}); 

关于php - Jquery 单击在下拉菜单上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9137505/

相关文章:

php - 防止 curl 为较大的文件生成 fatal error

javascript - 我怎样才能使整个表格行可点击,以便它选中一个复选框并更改按钮的颜色?

javascript - 在 For 循环中分配 JQuery On Click 函数

非 OOP 程序员的 PHP 框架

php - Laravel 5 withInput old 总是空的

php - 用于计算 mySQL 表中行数的 Wordpress 函数/插件

php - ajax 帖子未返回成功

jquery - CSS 多图像转换 - 需要想法

asp.net - 如何获取链接按钮的 url

java - Android自定义双击位置