在我的 div 中,我想观察他的类,所以当这个类$('#add_favourite').on('click', function (event) {
event.preventDefault();
$('#log').text('add');
update_favourite('add');
});
function update_favourite(addOrRemove) {
if ($('#add_favourite').length) {
$('#add_favourite').off('click');
console.log('add favourite is being removed');
$('#submitbutton').val('Remove from Favourites');
$('#add_favourite').attr("id", "remove_favourite");
$('#remove_favourite').on('click', function (event) {
event.preventDefault();
$('#log').text('remove');
console.log('remove');
update_favourite('remove');
});
} else if ($('#remove_favourite').length) {
console.log('remove favourite is being removed');
$('#remove_favourite').off('click');
$('#submitbutton').val('Add to Favourites');
$('#remove_favourite').attr("id", "add_favourite");
$('#add_favourite').on('click', function (event) {
event.preventDefault();
console.log('add');
update_favourite('add');
});
}
}
添加到我的div中时,我会执行一些js函数。
初始div:passed
添加新课程后:<div id="1" class="allow"></div>
我的执行功能:
<div id="1" class="allow passed"></div>
答案 0 :(得分:0)
您还可以在该div上使用变异观察器来检测何时添加类。请注意变异观察者的使用.. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === "class") {
if ($(mutation.target).hasClass('passed')){
alert("passed class was added");
fill();
}
}
});
});
observer.observe(document.getElementById('1'), {
attributes: true
});
这是一个jsfiddle https://jsfiddle.net/e37am2hq/