我有一个类似于 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/