Javascript 反对';挂钩';进入jQuery函数,可能吗?
我目前遇到以下问题,我想更优雅地解决: 我的脚本如下所示:Javascript 反对';挂钩';进入jQuery函数,可能吗?,javascript,jquery,hook,iteration,Javascript,Jquery,Hook,Iteration,我目前遇到以下问题,我想更优雅地解决: 我的脚本如下所示: 需要一个元素 使用.append() 跟踪容器“填充”的距离 如果容器已满,克隆一个新容器并继续 重复此操作,直到处理完每个元素 现在,这要求我跟踪一个“fill”(和一个“max”)变量,以确定容器已填充的距离。因此每次执行append(),我都必须递增这些计数器 现在,对我来说更优雅的是使容器对象智能化,并使其能够“钩住”到append()事件中:每当追加某个内容时,容器对象本身就会执行一些代码(增加其自身的计数器,决定它是否已满,
.append()
克隆一个新容器并继续
append()
,我都必须递增这些计数器
现在,对我来说更优雅的是使容器
对象智能化,并使其能够“钩住”到append()
事件中:每当追加某个内容时,容器对象本身就会执行一些代码(增加其自身的计数器,决定它是否已满,如果已满,则返回一个新的空容器)
我想通过创建一个返回容器的函数来解决这个问题:
var container = {
template : $('<div class="container"></div>'),
containers : [],
get : function (i) {
if (!this.containers[i]) {
this.containers[i] = this.template.clone()
.addClass('container-'+i)
.data('max', 500); //this determines the maximum (px) the container can hold
}
return this.containers[i];
}
};
(function($)
{
var oldappend = $.fn.append;
$.fn.newAppend = function()
{
var ret = oldappend.apply(this, arguments);
//your logic goes here
if (!this.count){
this.count = 0;
}
this.count++;
return ret;
};
})(jQuery);
var容器={
模板:$(''),
集装箱:[],
get:函数(i){
如果(!this.containers[i]){
this.containers[i]=this.template.clone()
.addClass('container-'+i)
.data('max',500);//这决定了容器可以容纳的最大值(px)
}
归还这个。容器[i];
}
};
这是可行的,因为我现在可以迭代所有元素,并为每个元素调用container.get(I).append(element)
(同时分别保留高度计数并将其与container().get(I).data().max
)进行比较),然后在脚本中,当我需要输出时,我可以返回container.containers
对象
但是我不能让它使用容器。让函数“监视”一个append()
并执行它。我知道这不是jQuery的工作方式,但我确信还有另一种方法,除了在元素迭代器中保留本地计数器之外
我尝试的另一件事是在($.append,function(){//do stuff});
容器上设置,但那是一个白日梦
我希望我已经解释清楚了所有的事情,并且很想知道是否有人能解决这个问题
一个“有效”的例子(我非常怀疑我的编程技能)也许你需要这样的东西:
(function($)
{
var oldappend = $.fn.append;
var count = 0;
$.fn.newAppend = function()
{
var ret = oldappend.apply(this, arguments);
//your logic goes here
// count++;
return ret;
};
})(jQuery);
或者,您需要存储每个容器的计数变量:
var container = {
template : $('<div class="container"></div>'),
containers : [],
get : function (i) {
if (!this.containers[i]) {
this.containers[i] = this.template.clone()
.addClass('container-'+i)
.data('max', 500); //this determines the maximum (px) the container can hold
}
return this.containers[i];
}
};
(function($)
{
var oldappend = $.fn.append;
$.fn.newAppend = function()
{
var ret = oldappend.apply(this, arguments);
//your logic goes here
if (!this.count){
this.count = 0;
}
this.count++;
return ret;
};
})(jQuery);
使用它:
$('<div class="container"></div>').newAppend(yourElement);
$('').newAppend(yourElement);
这很聪明,为什么我没有想到设计一个新的append函数的原型:)这看起来很不错。让我尝试将其集成到代码中如何引用从newAppend函数中放入的元素?('yourElement')在您的代码编辑中:没关系,通过更改为'$.fn.newAppend=function(element)')在本例中,参数[0]@c_kick:yes:function(element)和参数[0]指的是同一件事。