Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当由ajax显示时,元素不能绑定Javascript事件_Javascript_Ajax_Html Lists_Event Listener - Fatal编程技术网

当由ajax显示时,元素不能绑定Javascript事件

当由ajax显示时,元素不能绑定Javascript事件,javascript,ajax,html-lists,event-listener,Javascript,Ajax,Html Lists,Event Listener,好的,我有一个下拉菜单,通过UL和LI的标签显示。它是通过一个php脚本呈现的,该脚本响应: '<li id='. $value .'>'.$value.'</li>' 既然您说列表是动态更改的,那么您可能需要使用事件委派(用于jquery>=1.7)和live for更早的版本。试试这个: $(document).on('click', 'li' , function() { // Change document to ul or any other contain

好的,我有一个下拉菜单,通过UL和LI的标签显示。它是通过一个php脚本呈现的,该脚本响应:

'<li id='. $value .'>'.$value.'</li>' 

既然您说列表是动态更改的,那么您可能需要使用事件委派(用于jquery>=1.7)和live for更早的版本。试试这个:

$(document).on('click', 'li' , function() { // Change document to ul or any other container that exists in DOM at any time to have the event delegated to li's
    //anything
    alert('works');
} 
在您的案例中可能发生的情况是,当您绑定click事件时,它们只绑定到DOM中当时存在的li。但稍后通过AJAX调用动态更新/添加li,直接在li上进行的常规事件绑定将不会应用于此。因此,您只需将事件绑定到另一个类似容器的ul或DOM中随时存在的任何其他对象,或者绑定到文档头,这样现在或将来创建的li就可以通过委托获得click事件

$('li').click(function() {
    //anything
    alert('works');
} 
单击“仅适用于页面上已存在的项目”

如果在连接处理程序后添加了内容,则使用on

$('ul').on('click','li',function() {
    //anything
    alert('works');
});
$'li'。单击仅影响页面上已存在的元素。试着这样做:

$('ol,ul').on('click','li',function() {...});

这将为运行时存在的单击处理程序设置单击处理程序。如果以后添加更多,它们将不会自动附加单击处理程序

$('li').click(function() {
    //anything
    alert('works');
}   
从这一点开始:

<ul id=container>
  <li>Option 1</li>
</div>
添加到的任何元素都将自动获得单击处理程序功能

<ul id=container>
  <li>Option 1</li>
</div>
$('#container').on('click','li', function() {
   // do your stuff here. **this** points to the clicked <li>
});