// Get the modal
    var modal = document.getElementById('bozy-mymodal');
    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var img = document.getElementById('bozy22-popup');
    var modalImg = document.getElementById("image-01");
    var captionText = document.getElementById("caption");
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }


此代码位于WordPress主题的我的custom.js中,它处理图像Popup,但在首页上,其他页面甚至无法处理其他Jqueries或用custom.js编写的自定义查询。 t执行诸如Popmenu等。解决方案是什么?

Uncaught TypeError: Cannot set property '**onclick**' of null
    at custom.js:20
    at custom.js:44


那似乎是在寻找名为body22-popup的图像,该图像在该页面上不存在,但在滑块可工作的页面上存在。

var img = document.getElementById('body22-popup');


类似的情况在这里→
i'm getting an Uncaught TypeError: Cannot set property 'onclick' of null?

有没有一种方法可以在custom.js中执行代码的那部分,而这种地方可能不会弹出。

在Wordpress中,这样添加脚本→

wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
        wp_enqueue_script( 'custom-js' );

最佳答案

因此,在尝试分配处理程序之前,请确保img不为null:

...
var img = document.getElementById('bozy22-popup');
if ( img )
{
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }
}

10-04 22:09
查看更多