最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

block editor - How to add classes and events to image in javascript using Gutenberg?

matteradmin8PV0评论

Before WordPress 5.0, manipulating the content in the editor using javascript was fairly easy:

  • add_wp_tiny_mce_init_script to add your script in the TinyMCE iframe
  • profit

The script I include in TinyMCE gets all the img elements and adds an error handler onto them:

jQuery(document).ready(function($) {

    $('img').each(function(index, el) {
        var img = $(el);
        console.log(img);
        $('<img/>').on('error', function() { handleError(img); }).attr('src', img.attr('src'));
    });

    function handleError(media) {
        // do stuff
    }
}

It allows me to detect broken images (only those with a specific class), add a new class to them, change the href dynamically to show a fallback, and trigger an alert telling the editor to re-insert the image - easy.
A similar operation is done on the frontend on images with the aforementioned class to try and load a fallback as well.

Now, with WordPress 5.0, the script is included in TinyMCE (for blocks using the Classic Editor), AND on the page itself ; but that bit doesn't get the images inserted in the Gutenberg blocks:

$('img').each(function(index, el) {
    var img = $(el);
    console.log(img);
    $('<img/>').on('error', function() { handleError(img); }).attr('src', 
 img.attr('src'));
});

This is because when the script is running, the DOM is not loaded yet. I also noticed that directly manipulating the HTML rendered on the page doesn't work anyway (add a class to an image in the inspector > save post > reload > class was not saved).

What would be the proper way to:

  • add events to and manipulate attributes of images present in Gutenberg-created blocks?
  • getting these changes actually saved when the changes are submitted?
Post a comment

comment list (0)

  1. No comments so far