繁体   English   中英

为什么this.parent()不是定义为函数?

[英]Why isn't this.parent() defined as a function?

的jsfiddle

我正在创建一个新的按钮元素

$('<button>Remove Entry</button>', { 'type': 'button', 'class': 'delete_button' });

然而,似乎没有定义typeclass属性,并且控制台打印出一个错误,说明this.parent()不是一个函数(虽然我很肯定我启用了jquery)

我担心我做了一些简单而愚蠢的事,但我似乎找不到任何错误。

未在元素上设置属性的原因是您混合使用jQuery方法的不同用法。

要以使用对象作为属性的方式使用该方法,第一个参数应该是单个标记,而不是HTML片段:

$('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');

this没有parent方法的原因是它引用了一个元素,而不是一个jQuery对象。 你可以使用$(this)从元素引用中创建一个jQuery对象。

此外,当您绑定事件时调用方法时, this引用新的条目按钮,而不是删除条目按钮。 您应该在事件发生时调用该方法:

delete_button.click(function() {
  remove_entry($(this).parent())
});

演示: http//jsfiddle.net/Guffa/9TcpB/1/

  var entries = 0; function new_entry() { entries++ new_entry_div = $('<div>', { 'class': 'entry' }).appendTo('form'); new_entry_div.html('<p><input type="text"></p>') // delete button delete_button = $('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry'); delete_button.appendTo(new_entry_div); delete_button.click(function(){ remove_entry($(this).parent()); }); } function remove_entry(entry) { entry.remove(); } $("#newButton").click(function () { new_entry(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="input"> <form> </form> <button id="newButton">New Entry</button> </div> 

你基本上是这样做的

$("#newButton").click(function() {
    new_entry;
});

function new_entry() {
    this.parent();
}

但是在事件处理程序的回调中, this是本机JS DOM元素,而不是jQuery对象,所以它没有jQuery方法,你必须先将它包装起来,就像在

$("#newButton").click(new_entry);

function new_entry() {
    $(this).parent();
}

this包含一个DOM元素。 如果要使用jQuery方法,则必须使用$(this)将其转换为jQuery对象。

jsFiddle Demo

使用call方法保留当前上下文:

$("#newButton").click(function () {
  new_entry.call($(this));//now this in new_entry refers to `$(this)`
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM