javascript onclick function null
javascript onclick function null
我有以下js函数:
function Modification_Article()
{
var photo = document.getElementById("photo_javascript");
photo.innerHTML = "";
document.getElementById("photo_delete_javascript").innerHTML = "";
var loop = 0;
for(loop = 0; loop < arguments.length; loop++)
{
if(loop < 3)
{
document.getElementById('Modification_Article_Id').value = arguments[loop];
document.getElementById("Modification_Article_Titre").value = decodeURIComponent(arguments[loop + 1]);
document.getElementById("Modification_Article_Text").value = decodeURIComponent(arguments[loop + 2]);
loop += 2;
}
else
{
var image_to_delete = document.createElement('img');
var path = arguments[loop + 1];
var begin = path.substr(0, 32);
var end = path.substr(32);
var id = arguments[loop];
console.log(id);
image_to_delete.id = "image_" + id;
image_to_delete.src = "images/Articles/" + begin + "_100x100" + end;
image_to_delete.onclick = function(){ console.log(id); };
photo.appendChild(image_to_delete);
loop += 1;
image_to_delete = null;
}
}
}
事实是,当我第一次打印"id"时,它显示"10"answers"11"(根据照片的id),但第二次在onclick函数中,只有"null"显示。我真的不明白为什么…
在onclick函数中使用id
有一个问题:在创建的每个IMG元素中,您都引用相同的变量。
我认为你期望,当id
在onclick函数中被引用时,它以某种方式被函数复制和记住。但事实并非如此,它引用了相同的变量,并且该变量的值与上次迭代时相同。
要解决这个问题,你可以使用这样的命令:
(function(id){
image_to_delete.onclick = function(){ console.log(id); };
})(id);
在上面的代码中,通过将id变量作为包装函数参数传递,生成了一个副本。
相关文章:
- 数组在递归方法中设置为null
- 直接在函数声明上使用function.prototype.bind
- jQuery:.click(function(){(element),collapse('show',f
- 字符串在将其传递给另一个活动Android JavaScript时读取Null
- 无法获取属性'selectedIndex'的未定义引用或null引用
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 来自文本输入null的html javascript变量
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- php代码在textbox更改事件上显示null
- 相同的RegExp返回不同的结果-第一次是正确的结果,第二次是null
- 如果连接类型为none,则Javascript Function Only警报
- 在php中提交数据时,如果某些值为null,而某些值为非null,如何进行查询
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- 为什么localStorage[“..”]未定义,而localStorage.getItem(“..”)为null
- ajax在输入等于null时进行检查
- 财产的价值'openNewWin'为null或未定义,而不是Function对象
- 为什么会失败: 'function log(){console.log.apply(null,arguments);}`
- Function.prototype.bind with null 作为参数
- (function() { document.getElementById() == null; })();
- javascript onclick function null