开发者

Click event on dynamic element WITHOUT jQuery

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?

document.getElementById('create').onclick = function(){
    var newdiv = document.createElement('div');
    newdiv.addClass('new');
    document.body.appendChild(newdiv);
};

document.getElementsByClassName('newdiv').onclick = function(){
    alert('Success');
};
    
    
#create {
     width:150px;
     height:25px;
     margin-bottom:5px;
     background:#ccc;
     border:1px solid #222;   
}

.new {
    width:200px;
    height:100px;
    background:#ffccff;
    border:1px solid #333;   
}
<html>
    <body>
        <div id="create">
            Click to create div
        </div>
    </body>
</html>

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

Any help would be gre开发者_开发问答atly 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.


@Anurag's answer is correct but not complete and in most cases will result a lot of integration bugs.

Here is the correct version:

document.addEventListener("click", function(event)
{
    // retrieve an event if it was called manually
    event = event || window.event;

    // retrieve the related element
    var el = event.target || event.srcElement;

    // for all A tags do the following
    if (el instanceof HTMLAnchorElement )
    {
        //required to make the "return false" to affect
        event.preventDefault();

        window.location.href = "/click.php?href="+encodeURIComponent(el.href);

        //prevent user's click action
        return false;
    }
}, true);

This is a basic click-trace functionality affects all links on page to trace/record all link clicks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜