为什么 this.parent() 没有定义为函数?



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)`
})

最新更新