简体   繁体   English

jQuery — append(),然后是.click()+ $(this).parent()

[英]jQuery — append(), then .click() + $(this).parent()

Is there a way to add a click function to an appended html element? 有没有一种方法可以将click函数添加到附加的html元素? Additionally, is it possible to do something to the parent of that appended element? 另外,是否可以对该附加元素的父元素执行某些操作? For example, add or remove a class of its immediate parent? 例如,添加或删除其直接父级的类?

Here's some pseudo code: 这是一些伪代码:

// Jade //玉

.container.test

  .content
    | Some content

// JS // JS

$('.content').append('<button>Button</button>')

$('button').on('click', function() {
  $(this).parent('.container').removeClass('test')
})

Yes. 是。

var $button = $('<button>').text('Button');
$('.content').append($button);

$button.on('click', function() {
  $button.parent('.container').removeClass('test')
})

This is why it's best practice to create HTML elements using jQuery (or another library of your choice) and then append/prepend/replace the element, instead of appending/prepending/replacing raw HTML strings. 这就是为什么最佳做法是使用jQuery(或您选择的另一个库)创建HTML元素,然后附加/添加/替换元素,而不是附加/添加/替换原始HTML字符串。

You could also do something like below: 您还可以执行以下操作:

$('.content').append($('<button>Button</button>').click(function() {
   $(this).parent('.container').removeClass('test');
}));

Another solution is to use event delegation (bind event on document ). 另一个解决方案是使用事件委托(在document上绑定事件)。

$('.content').append('<button>Button</button>');

$(document).on('click', '.content button', function() {
  $(this).parent('.container').removeClass('test');
});

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

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