是否可以使用jquery函数(如委托)来监听jquery ui事件? [英] Is it possible to use a jquery function such as delegate to listen to jquery ui events?

查看:125
本文介绍了是否可以使用jquery函数(如委托)来监听jquery ui事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用像 .delegate()这样的函数, .on()或以任何方式监听jquery UI事件,例如 draggable 。我有以下内容:

i want to know if its possible to use a function like .delegate(), .on() or any in a way that it will listen to jquery UI events such as draggable. I have the following:

HTML:

  <div id="wrapper"></div>​

javaScript:

javaScript:

$(function(){

  var addMe='<div id="draggable" class="ui-widget-content"><p>Drag me around</p></div>'

  $( "#wrapper" ).delegate('#draggable','draggable',function(){
       console.log('its something!');
  });

  //$(".draggable").draggable();
  $("#wrapper").append(addMe) 
})

元素将是 draggable 是动态添加的,这样我就可以使用委托

The element that is going to be draggable is dynamically added so that is way i want to use delegate or on.

另请注意,我知道如何从.ajax GET的结果中添加可拖动的列表项?甚至该解决方案对我来说也很有用修改.post()函数,这不是我要问的。

Also note that i'm aware of How do I add draggable List Items from the result of a .ajax GET? and even that solution can work for me i have to modify the .post() function which is not what i'm asking.

这是问题

推荐答案

这是一个非常常见的问题....使用委托来调用插件,并且没有像 on()那样的圣杯。在几乎所有jQueryUI小部件的情况下,涉及的内容远比简单绑定事件要多得多,需要对html和元素数据进行修改。

This is a very common question....how to use delegation to invoke plugins , and there is no holy grail like on(). In the case of almost all jQueryUI widgets there is far more involved than simply binding events, the html and element data needs to be connstructed.

虽然没有委托方法,你可以使用$ .ajaxComplete()作为全局处理程序来初始化插件,如果它适合你的应用程序。它可以绑定到任何元素,允许在处理程序中使用 this

ALthough there is no delegation method, you can use $.ajaxComplete() as a global handler to initialize plugins , if it suits your application. It can be bound to any element, which allows using this within handler

 $('#content').ajaxComplete(function(e, xhr, settings){
     /* url conditional*/
      if (settings.url == 'getMoreDraggables.php') {
            $(this).find('.newDraggable').removeClass('newDraggable').draggable()
      }
      /* element conditional */
     if( $(this).find('.newDraggable').length){  
        /* run code for true*/
     }

});

还可以根据xhr对象添加条件

Can also add conditionals based on xhr object

这篇关于是否可以使用jquery函数(如委托)来监听jquery ui事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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