单击时JQuery没有检测到我的DOM对象

时间:2014-11-12 17:16:47

标签: javascript jquery ajax

在弄清楚这里出了什么问题时会遇到一些麻烦,并想知道是否有人可以帮助我。我在我的网站上使用JQuery但由于某种原因,在这个特定页面上它似乎没有用。

这段代码:

$("#keyword").autocomplete({                        
    source:'../../pages/ajax/autocomplete/autocomplete_tags.php',
    dataType: 'json',
    minLength:1
});

//When you hit the search button load the new tags
$("#srchBtn").click(function(e){
    e.preventDefault();
    var tag_name = $('#keyword').val();
    $(".dashboardtable").load('../../pages/ajax/autocomplete/search_tags.php', {tag_name: tag_name },function(response, status, xhr){
            $(".dashboardtable").html(response);
            $("#keyword").val("");
            $("#keyword").attr("placeholder", "Search Tags...");
    });
});

当用户开始输入时,应该发生的事情是开始从数据库中提取建议,当他们点击搜索按钮时,会使用AJAX将结果加载到div中。我注意到它没有工作,我决定尝试一个简单的测试:

$('#srchBtn').click(function(){
    console.log('hit');
})

但控制台中没有任何内容。然后我尝试了

console.log($('#srchBtn'));它似乎确实引用了我的dom对象,它只是因为某些原因而没有触发click事件。

我在页面顶部找到了以下scripts

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script> 
 <script src="../scripts/auto-complete/tag_list_search.js"></script>

我的控制台中没有错误。那可能是什么问题呢?任何帮助深表感谢。这也是我的HTML

<input type="text" id="keyword" placeholder="Search Tags..." size="33"/>
<input type="button" class="" id="srchBtn" value="Search"/>

1 个答案:

答案 0 :(得分:0)

Please wrap the code in jquery ready function...(in case this is not done)

$(function(){ // jquery ready function
$("#keyword").autocomplete({                        
    source:'../../pages/ajax/autocomplete/autocomplete_tags.php',
    dataType: 'json',
    minLength:1
});

//When you hit the search button load the new tags
$("#srchBtn").click(function(e){
    e.preventDefault();
    var tag_name = $('#keyword').val();
    $(".dashboardtable").load('../../pages/ajax/autocomplete/search_tags.php', {tag_name: tag_name },function(response, status, xhr){
            $(".dashboardtable").html(response);
            $("#keyword").val("");
            $("#keyword").attr("placeholder", "Search Tags...");
    });
});
});