使用JavaScript创建元素时如何添加onclick事件? [英] How to add onclick event while creating an element with JavaScript?

查看:68
本文介绍了使用JavaScript创建元素时如何添加onclick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以在其中将元素添加到列表中.我需要在单击元素时调用一个函数,为此函数需要在创建li时使用变量的值(这是li内容).

I have a script where I'm appending elements to a list. I would need that when I click the element a function is called, and for this function the value of a variable when creating the li is needed (it's the li content).

我已经检查了添加newLi.onclick = function(){...}之类的解决方案.

I've checked solutions like adding newLi.onclick = function(){...}.

此解决方案的问题是我没有在函数中获得正确的值,而是获得列表中另一个元素的值.

The problem with this solution is that I'm not getting the right value in the function, I get the value of another element in the list.

现在这是我创建元素的方式:

Right now this is how I'm creating the elements:

var ULlist = document.getElementById('ULid');
for(i=0;i<data.length;i++){
   var Value = data[i] //function to get data
   var newLi = document.createElement('li');
   newLi.appendChild(elements.createTextNode(Value));
   newLi.onclick = function(){alert(Value)} //not displaying the right value
   ULlist.appendChild(newLi);
}

所以问题是,有什么方法可以创建te onclick事件,从而为元素赋予变量正确的值?

So the question is, is there any way to create te onclick event giving to the element the right value of the variable?

我添加了更多代码. 正在创建Li,并且正确显示了信息,唯一的问题是尝试创建事件时,它没有给出正确的值,该值应该是在li

I've added a portion more of code. Li's are being created, and information displayed correctly, the only problem is when trying to create the event that it's not giving the right value, that should be the value cointained at the li

推荐答案

您可以通过在内部创建函数并将值保留在该函数的范围内来实现此目的.

You can achieve this by creating function inside and keeping the value in the scope of that function.

var data = [10, 20, 30, 40, 50, 60, 70];
addItems = function() {
    var list = document.getElementById("list");
    for (var i = 0; i < data.length; i++) {
        var newLi = document.createElement("li");
        newLi.innerHTML = i + 1;
        list.appendChild(newLi);
        (function(value){
        newLi.addEventListener("click", function() {
           alert(value);
        }, false);})(data[i]);
    }

}​

jsfiddle: http://jsfiddle.net/Qf5JZ/1/

jsfiddle : http://jsfiddle.net/Qf5JZ/1/

这篇关于使用JavaScript创建元素时如何添加onclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆