Sna*_*awa 26 javascript jquery
在jquery中是否有一种方法可以监听节点类的更改,然后在类更改为特定类时对其执行某些操作?具体来说,我正在使用jquery工具选项卡插件和幻灯片放映,并且正在播放幻灯片时,我需要能够检测焦点何时在特定选项卡/锚点上,以便我可以取消隐藏特定的div.
在我的具体例子中,我需要知道何时:
<li><a class="nav-video" id="nav-video-video7" href="#video7-video">Video Link 7</a></li>
Run Code Online (Sandbox Code Playgroud)
添加了"current"类更改为以下内容:
<li><a class="nav-video" id="nav-video-video7 current" href="#video7-video">Video Link 7</a></li>
Run Code Online (Sandbox Code Playgroud)
然后我想在那一刻取消隐藏div.
谢谢!
小智 26
您可以绑定DOMSubtreeModified事件.我在这里添加一个例子:
HTML
$(document).ready(function() {
$('#changeClass').click(function() {
$('#mutable').addClass("red");
});
$('#mutable').bind('DOMSubtreeModified', function(e) {
alert('class changed');
});
});Run Code Online (Sandbox Code Playgroud)
JavaScript的
<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>Run Code Online (Sandbox Code Playgroud)
我知道这已经过时了,但接受的答案使用DOMSubtreeModified,它现在已被弃用MutationObserver。这是一个使用 jQuery 的示例(在此处进行测试):
// 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();
Run Code Online (Sandbox Code Playgroud)
以下是可能提供解决方案的其他一些发现:
\n\n\n\n正如 #2 中所建议的,为什么不创建current一个添加的类而不是 ID,并让以下 CSS 处理显示/隐藏操作。
<style type=\'text/css>\n .current{display:inline;}\n .notCurrent{display:none;}\n</style>\nRun Code Online (Sandbox Code Playgroud)\n\n可能还值得研究一下jquery 中的 .on()。
\n