手柄点击事件jQuery中附加元素。 [英] Handle click event for appended elements in jQuery

查看:114
本文介绍了手柄点击事件jQuery中附加元素。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经生成使用下面的方法在我的网页几个要素。例如,

I have generated few elements in my page using following method. For example,

$("#button"+caption).click(function(){
        var firstDisplay = '<div id="firstDisp'+caption+'"><ul>';
        for(var i=0;i<parents.length;i++){
            firstDisplay=firstDisplay+'<li class="fClick">'+parents[i]+'</li>';
        }
        firstDisplay=firstDisplay+'</ul></div>';
        $(firstDisplay).dialog();
});

当我为'FCLASS像这样建立一个onclick事件:

and when i create an onclick event for 'fClass' like so :

$(".fClick").click(function(){
    alert("hey!");
}); 

它不工作!但是,如果我把的onclick函数其他函数中,后.dialog()吧,它的作品!我有很多这种方式创建的元素,所以我不能把所有的onclick事件在一个单一的方法。有没有解决这个办法吗?我有.append方法相同的问题也是如此。

It does not works ! However, if i put the onclick function inside the other function, right after .dialog(), it works ! I have a lot of elements created this way, so I cannot put all onclick events in a single method. Is there any way around this? I am having the same problem with .append method as well.

推荐答案

将其更改为。对 .delegate 基于jQuery的版本,您正在使用。

Change it to .on or .delegate based on the version of jQuery you are using..

在jQuery 1.7 +

$(document).on('click', '.fClick', function(){ 
    alert("hey!");
}); 

对于老版本的jQuery使用代理

For older jQuery versions use delegate

$(document).delegate('.fClick', 'click', function(){
    alert("hey!");
}); 

这篇关于手柄点击事件jQuery中附加元素。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆