使用外部函数处理jQuery事件

使用外部函数处理jQuery事件,jquery,Jquery,我想运行一个简单的脚本,它将html元素添加到div中 我想多次调用这个函数,所以我使用了this关键字 我的代码是: function insert(element, html) { $( html ).appendTo( element ); } $('#div').bind('click', insert(this,'<p>inserted text</p>')); 函数插入(元素,html){ $(html).appendTo(元素); } $('#d

我想运行一个简单的脚本,它将
html
元素添加到
div

我想多次调用这个函数,所以我使用了
this
关键字

我的代码是:

function insert(element, html) {
    $( html ).appendTo( element );
}

$('#div').bind('click', insert(this,'<p>inserted text</p>'));
函数插入(元素,html){
$(html).appendTo(元素);
}
$('#div').bind('click',insert(这个,插入的文本)

);

不知怎么了,谢谢。

jQuery
bind
希望第二个参数是
函数
,但您传递的是
insert
函数的返回值(在您的情况下,该函数是
未定义的,因为它不返回任何内容)

你真正想要的是:

function insert(element, html)
      {
      $( html ).appendTo( element );
      }

$('#div').bind('click', function() { insert(this,'<p>inserted text</p>'); });
函数插入(元素,html)
{
$(html).appendTo(元素);
}
$('#div').bind('click',function(){insert(this,inserted text

);});
或:

函数插入(html)
{
返回函数(){$(html).appendTo(this);};
}
$('#div').bind('click',insert('p>inserted text

);
$(html).appendTo($(元素))

问题在于,您没有将回调函数传递给
bind
,而是传递了调用该函数的结果。显然,这不是您在这里试图实现的目标,这是开始jQuery开发人员的常见错误。这种情况非常普遍,他们甚至将其放入(请参阅回调和函数>带参数的回调)。顺便说一下,这是一本推荐书

您需要传递一个调用
insert的函数(这是,inserted text

执行时。因此,这看起来像:

$('#div').bind('click', function() {
    insert(this, '<p>inserted text</p>');
});
$('div').bind('click',function(){
插入(此“插入文本”

); });

事件处理程序被绑定到受影响的DOM元素,用于它们的
this
上下文,我相信这就是您在这里要做的。如果没有,则需要使用一些技巧(例如
Function.prototype.bind
jQuery.proxy
)来“修复”事件处理程序的
上下文。

您正在调用
插入
,并尝试将返回值(
未定义
)绑定为事件处理程序。您必须将函数传递给
bind
。只有在该函数(即事件处理程序)内部,
将引用已单击的元素。请看,不。传递给
.appendTo
的参数可以是DOM元素。它不必是jQuery对象。您的“解决方案”将等同于OP已有的解决方案。对不起,我是jQuery中的新手,但当我在firebug中运行此脚本时,它显示0个错误。
$('#div').bind('click', function() {
    insert(this, '<p>inserted text</p>');
});