对于任何使用古腾堡编辑器的人来说,我发现(除了我对公认答案的评论之外)这里还有更多的工作需要做。
古腾堡给儿童注射.block-editor__container
因此,仅仅修改选择器来捕捉更改事件是不够的,您必须注意插入的元素是否正确。使用MutationObserver (因为这是一种更好的实践,它取代了很快被弃用的DOM突变事件,并且full browser support), 这就是我如何完成捕获模板更改的过程:
$ = $ || jQuery; // Allow non-conflicting use of \'$\'
$(function(){
// Create an observer to watch for Gutenberg editor changes
const observer = new MutationObserver( function( mutationsList, observer ){
// Template select box element
let $templateField = $( \'.editor-page-attributes__template select\' );
// Once we have the select in the DOM...
if( $templateField.length ){
// ...add the handler, then...
$templateField.on( \'change\', function(){
// ...do your on-change work here
console.log( \'The template was changed to \' + $( this ).val() );
});
observer.disconnect();
}
});
// Trigger the observer on the nearest parent that exists at \'DOMReady\' time
observer.observe( document.getElementsByClassName( \'block-editor__container\' )[0], {
childList: true, // One of the required-to-be-true attributes (throws error if not set)
subtree: true // Watches for the target element\'s subtree (where the select lives)
});
});
希望这对别人有帮助!