如何用jQuery为动态添加的元素的修改样式
可以使用以下方法:
- 使用on()方法,将事件委托给已存在的父元素,当子元素被添加时也能够响应事件。
$(document).on('click', '.new-element', function(){
$(this).addClass('new-style');
});
- 在动态添加元素的函数中,添加样式。
function addElement() {
var newElement = $('<div class="new-element">New Element</div>');
newElement.css({'background-color': 'red', 'color': 'white'});
$('body').append(newElement);
}
- 在动态添加元素后,使用find()方法查找到新添加的元素,然后添加样式。
var newElement = $('<div class="new-element">New Element</div>');
$('body').append(newElement);
newElement.find('.child-element').css({'background-color': 'red', 'color': 'white'});
原文地址: https://www.cveoy.top/t/topic/bgfL 著作权归作者所有。请勿转载和采集!