在jquery中,有没有一种方法可以监听节点的类的更改,然后在类更改为特定类的情况下对其执行一些操作?具体地说,我在幻灯片中使用了jquery tools tabs插件,当幻灯片播放时,我需要能够检测到焦点在特定的选项卡/锚点上,这样我就可以隐藏特定的div。
在我的特定示例中,我需要知道何时:
<li><a class="nav-video" id="nav-video-video7" href="#video7-video">Video Link 7</a></li>
对以下内容进行了更改,并添加了"current“类:
<li><a class="nav-video" id="nav-video-video7 current" href="#video7-video">Video Link 7</a></li>
然后,我想在那个时刻显示一个div。
谢谢!
发布于 2013-07-26 20:40:01
您可以绑定DOMSubtreeModified
事件。我在这里添加一个示例:
$(document).ready(function() {
$('#changeClass').click(function() {
$('#mutable').addClass("red");
});
$('#mutable').bind('DOMSubtreeModified', function(e) {
alert('class changed');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mutable" style="width:50px;height:50px;">sjdfhksfh
<div>
<div>
<button id="changeClass">Change Class</button>
</div>
发布于 2018-12-14 03:21:24
我知道这是旧的,但公认的答案是使用DOMSubtreeModified
,它现在已经被MutationObserver
弃用。下面是一个使用jQuery (here测试)的例子:
// Select the node that will be observed for mutations
let targetNode = $('#some-id');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.attributeName === "class") {
var classList = mutation.target.className;
// Do something here with class you're expecting
if(/red/.exec(classList).length > 0) {
console.log('Found match');
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode[0], config);
// Later, you can stop observing
observer.disconnect();
发布于 2013-07-23 04:22:42
对于这种情况,您基本上有两个选择:回调或轮询。
由于您可能无法在DOM以这种方式(在所有平台上都可靠地)发生变化时触发事件,因此您可能必须求助于轮询。为了更好地使用它,您可以尝试使用requestAnimationFrame应用程序接口,而不仅仅是本机使用像setInterval这样的东西。
采用最基本的方法(即使用setInterval并假设使用jQuery),您可以尝试如下所示:
var current_poll_interval;
function startCurrentPolling() {
current_poll_interval = setInterval(currentPoll, 100);
}
function currentPoll() {
if ( $('#nav-video-7').hasClass('current') ) {
// ... whatever you want in here ...
stopCurrentPolling();
}
}
function stopCurrentPolling() {
clearInterval(current_poll_interval);
}
https://stackoverflow.com/questions/3731807
复制相似问题