jQuery .on('click') does not work with jQu

2019-09-17 19:26发布

问题:

I have a question regarding jQuery. I am really new with jQuery, or even javascript for that matter, so please bear with me.

I am using jQuery UI draggable on some divs in my app. The problem is, jQuery .on('click') doesn't seem to work with these divs. I did try to use .click() and it does work. However, the divs are going to be created dynamically, and based on what I've learned it is best to use .on() when we want to use dynamically created elements. Below is my HTML snippet:

<div class="book-page">
    <div class="draggable-text">
        <p>First text</p>
    </div>
    <div class="draggable-text">
        <p>Second text</p>
    </div>
</div>

And here is the jQuery snippet:

$('div.draggable-text').draggable({
    cursor: 'move',
    delay: 200,
    containment: 'parent'
}).resizable().selectable();

// This one doesn't work
$('div.book-page').on('click', 'div.book-page > div.draggable-text', function () {
    alert('clicked!');
    // some more coding here...
});

// This one works
/*$('div.book-page > div.draggable-text').click(function () {
    alert('clicked!');
    // some more coding here...
});*/

And lastly, here is a link to a jsfiddle I've created. I really appreciate any kind of help.

Thanks! And sorry for the bad English.

回答1:

Looks like you have some syntax errors with your second one.

Try this:

$('div.draggable-text').on('click', function () {
  alert('clicked!');
  // some more coding here...
});

Read the syntax for the jQuery 'on' event to understand better what arguments go in. http://api.jquery.com/on/

Cheers!



回答2:

Try this:

$('div.draggable-text').click(function(e){
e.preventDefault();
    alert('test');
});


回答3:

Jquery Syntax is incorect try this:

$('div.draggable-text').on('click', function () {
alert('clicked......');
// some coding here...
});

Check here : http://jsfiddle.net/jS8sK/2/



回答4:

If you want bind click event to dinamically created draggable element, your first idea was almost correct.

Here is a fixed code : http://jsfiddle.net/G75qs/3/

$('.draggable-text').draggable({
    cursor: 'move',
    delay: 200,
    containment: 'parent'
}).resizable().selectable();

//Bind click event for all element with class .draggable-text including 
//elements dynamically created
$('.book-page').on('click', '.draggable-text', function () {
    alert('clicked!');
    // some more coding here...
});


回答5:

for Divs that was created dynamically its better to use .live for events.

$('div.draggable-text').die('click').live('click', function () {
alert('clicked......');