jQuery:将事件处理程序添加到刚刚创建的元素中 [英] jQuery: adding event handler to just created element

查看:85
本文介绍了jQuery:将事件处理程序添加到刚刚创建的元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条声明添加了一个新的div:

I have a statement adding a new div:

$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');

但是我不仅要创建元素,还要为其分配on('click')操作. 当然,我可以添加生成的ID,然后通过该ID进入创建的元​​素,但是我觉得有更漂亮的解决方案.

But I'd like to not only create element but also to assign on('click') action to it. Of course I could add generated id and then acces to created element by this id, but I feel that there is more beautiful solution.

是吗?

推荐答案

您无需添加ID,然后让jQuery解析选择器以查找元素.您可以直接执行此操作:

You don't need to add an id and then ask jQuery to parse a selector to find the element. You can directly do this :

$('#dates').append(
    $('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>')
    .click(function(){
      // handle click
    })
);

这篇关于jQuery:将事件处理程序添加到刚刚创建的元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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