我有一张主照片的地方(id =" main")和表格中的其他照片(id =" pic + 1(2,3,4,5,6) &#34)。我想点击id =" pic n "并将其加载到id为" main"的元素中。怎么实现这个?
我也有错误
未捕获的TypeError:无法设置属性' onclick' null。
这是我的代码:
<img id="main" src="">
galery(dir){
...
...
function createPreview() {
var f = document.createElement("table");
var row = f.insertRow();
for(var j = 0; j < count ; j++) {
var cell = row.insertCell(j);
var img = new Image();
img.src = dir + '/' + j + ".jpg";
img.width = "100";
img.id = 'pic' + j;
cell.appendChild(img);
}
document.body.appendChild(f);
}
document.getElementById(this.pic).onclick = function() {
document.getElementById('main').src = this.src;
}
...
}
答案 0 :(得分:0)
您的代码中有很多错误:
1)在函数内部定义var f,因此其范围在函数内部。但是你试着把它带到document.body.appendChild(f);
的函数之外,这不起作用。你应该在函数内移动document.body.appendChild(f);
。
2)然后你得到Uncaught TypeError: Cannot set property 'onclick' of null.
因为document.getElementById(this.pic)
返回null。 this.pic不返回id。
3)关闭img tag
。
4)你还有2个}
如果您向我们展示您的所有代码,我相信还有更多。
答案 1 :(得分:0)
虽然你的代码有很多错误和对js如何工作的误解是一些解决这个问题的简单代码
//fake an image directory
var count = 3;
var dir = 'http://lorempixel.com/300/300/abstract/'
//setup a table
var f = document.createElement("table");
var row = f.insertRow();
for (var j = 0; j < count; j++) {
var cell = row.insertCell(j);
imagepath = dir + j;
cell.innerHTML = '<img src="' + imagepath + '" width="100" onclick="showmain(' + j + ')">';
}
document.body.appendChild(f);
//change imagesrc in main tag
function showmain(image) {
document.getElementById('main').src = dir + image;
}
这是你用javascript做的最基本的(noob)事情。
我强烈建议您在回答这些基本问题之前阅读更多教程。
这是Plunker。
没有onload处理程序,因此脚本位于页面的末尾。