【问题标题】:Uncaught TypeError: Cannot set property 'onclick' of null未捕获的类型错误:无法将属性“onclick”设置为 null
【发布时间】:2018-01-03 14:41:54
【问题描述】:
// 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 中,它处理图像弹出窗口,但在首页 opr 其他页面上,甚至没有其他 Jqueries 或自定义编写的自定义查询需要处理。 js不执行如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' );

【问题讨论】:

  • 检查图片标签必须有id body22-popup
  • 在var img = 的行之后,您可以添加console.log(img.length) 并在控制台窗口中告诉输出
  • 在执行代码之前对img做空检查?
  • @taplr,我是新手请详细解释一下。

标签: javascript jquery wordpress


【解决方案1】:

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

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

【讨论】:

  • 谢谢先生,让我试试这个。我会尽快上传你。
  • 我的。上传我在哪里..? :) -- 它会为你工作,首先检查 img 不会在页面上不存在点击处理程序时分配它,这意味着你的错误消失了。
  • 我在哪里测试和构建 wp 主题。
  • 这就是控制台现在的样子 → screencast.com/t/3Of4GZeOFC(如果像这样的故障排除有问题,我可以分享实时链接)
  • 不!你在分配它之前检查img,你将它分配inside if 条件,这是行不通的。
猜你喜欢
  • 2014-02-07
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2014-06-01
  • 2014-06-26
  • 2014-03-06
相关资源
最近更新 更多