在动态添加的元素上应用带有选项的jquery插件/功能 [英] Applying jquery plugin/function with options on dynamically added elements

查看:111
本文介绍了在动态添加的元素上应用带有选项的jquery插件/功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,有一个功能可以使用$(document).on(...)将事件也分配给html中新添加的元素,例如在ajax请求之后.

In jQuery there is a feature to use $(document).on(...) to assign a event also to the newly added elements in the html for example after ajax request.

您能否举一个将其与自定义函数/插件一起使用的示例,例如 hoverpulse .

Can you give an example of using this with a custom defined function/plugin for example hoverpulse.

我面临的另一个问题是,它还期望将某些值传递给该函数,该函数在选择器上调用它时由hoverpulse返回.

Other issue I am facing is that it is also expecting some values to be passed to that function which is returned by hoverpulse while calling it on the selector.

  $(document).ready(function(){  
    $('div.thumb img').hoverpulse({ size: 40, speed: 400 });   
  });

如何通过jQuery的on()方法传递此类函数的选项?请注意,这些选项不是传递给处理程序,而是函数hoverpulse本身.

How to pass the options of such function through on() method of jQuery? Note that the options are not to be passed to the handler but the function hoverpulse itself.

推荐答案

.on()方法用于分配事件处理程序,考虑使用它来应用插件没有意义.

The .on() method is used to assign event handlers, it doesn't make sense to be thinking about using it to apply a plugin.

如果我只使用$(selector).hoverpulse(),它将重新分配相同的功能...因此在某些情况下执行两次效果?"

是的,如果您使用相同的选择器,则会将该插件应用于当时与选择器匹配的所有元素,包括之前已完成的元素.对于某些插件来说可能没什么大不了的,但是对于其他插件而言却很重要.我对.hoverpulse()并不特别熟悉,但是可以想象,如果您多次对该元素调用.hoverpulse(),它可能会对同一元素多次执行效果.

Yes, if you use the same selector it will apply the plugin to all of the elements that match the selector at that time, including elements that were already done earlier. For some plugins that might not matter much, but for others it will. I'm not familiar with .hoverpulse() specifically, but conceivably it might execute the effect multiple times on the same element if you called .hoverpulse() multiple times for that element.

想到的第一个解决方法是将一个类添加到已经应用了插件的元素中,然后下一次将自己限制在没有该类的元素中:

The first workaround that comes to mind is to add a class to elements that have already had the plugin applied, then next time limit yourself to elements that don't have that class:

$('div.thumb img').not(".HPapplied")
                  .hoverpulse({ size: 40, speed: 400 })
                  .addClass("HPapplied"‌​);

鉴于您(大概)需要在文档准备就绪和Ajax成功回调中应用相同的选项,您可能希望将以上语句放入函数中,然后从两个地方调用该函数.这样,如果您需要更改其中一个选项,则只需将其更改为一个位置即可.

Given that you (presumably) need to apply the same options both in document ready and in your Ajax success callback you might like to put the above statement into a function and then call that function from both places. That way if you need to change one of the options you only have to change it in one place.

这篇关于在动态添加的元素上应用带有选项的jquery插件/功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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