点击事件动态元素WITHOUT jQuery [英] Click event on dynamic element WITHOUT jQuery

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

问题描述

我想添加一个事件,如onclick或mouseover到一个动态创建的元素(类似于.jive中的.live函数)...如何使用纯JavaScript没有框架,如jQuery?这是一个简单的jsFiddle http://jsfiddle.net/3tBpv/1/



我希望能够从新创建的div类而不是id。



任何帮助都会很大赞赏

解决方案

在文档对象上创建一个处理程序。检查目标元素的类和节点名称(tag)。如果他们匹配,请继续执行任何需要完成的操作,否则忽略点击。

  document.onclick = function(event){ 
var el = event.target;
if(el.className ==new&" el.nodeName ==DIV){
alert(div.new clicked);
}
};

这是一个小提琴


I would like add an event such as onclick or mouseover to a dynamically created element (similar to the .live function in jQuery)...how do I do this using pure javascript without a framework such as jQuery? Here is a simple jsFiddle http://jsfiddle.net/3tBpv/1/

I would like to be able to do this from the newly created divs class instead of an id.

Any help would be greatly appreciated

解决方案

Create one handler on the document object. Check the target element's class and node name (tag). If they match, proceed with whatever needs to be done, otherwise ignore the click.

document.onclick = function(event) {
    var el = event.target;
    if (el.className == "new" && el.nodeName == "DIV") {
        alert("div.new clicked");
    }
};

Here's a fiddle.

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

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