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

2019-09-17 19:49发布

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.

5条回答
唯我独甜
2楼-- · 2019-09-17 20:09

Jquery Syntax is incorect try this:

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

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

查看更多
爷的心禁止访问
3楼-- · 2019-09-17 20:13

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

$('div.draggable-text').die('click').live('click', function () {
alert('clicked......');
查看更多
乱世女痞
4楼-- · 2019-09-17 20:21

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!

查看更多
贪生不怕死
5楼-- · 2019-09-17 20:25

Try this:

$('div.draggable-text').click(function(e){
e.preventDefault();
    alert('test');
});
查看更多
聊天终结者
6楼-- · 2019-09-17 20:25

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...
});
查看更多
登录 后发表回答