简体   繁体   中英

Triggering Event When Div of Class “.x” is Clicked Using JQuery

JS:

$(".x").click(function()
    {
        alert("hello");
        return false;
    });


$("#otherdiv").html("<div class='x'>Drag and drop values on the right to create a pivot table.</div><br />");

CSS:

div.x
{
    background-color: white; 
    border: dotted 1px; 
    cursor: pointer;
    width: auto;
    float: left;
    position: absolute;
    top: 15%;
    left: 10%;
    padding: 10px;
}

When I click the div with the class 'x', nothing happpens.

You can't attach the event handler with click , because your <div> is added dynamically. The click method only works existing elements. You have to use live [ API Ref ] or delegate [ API Ref ] instead.


UPDATE: From jQuery's live documentation:

As of jQuery 1.7 , the .live() method is deprecated. Use .on() [ API Ref ] to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live() .

I think you need to use the jQuery.live() function, which also attaches the event to all elements created in the future.

http://api.jquery.com/live/

use delegate on body or container for.x class divs like: http://jsfiddle.net/MEEHN/

$('body').delegate('.x','click',function(){
   alert(1);
});

$('<div class="x">asd</div>').appendTo('body');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM