【发布时间】: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