Onclick选择从For循环中生成的HTML元素传递不正确的值

时间:2014-02-24 01:48:46

标签: javascript for-loop onclick

正如标题所说,我的onclick事件不断传递不正确的值 - 当显示多个选项时,它会传递第一个而不是选定的一个。这是我的相关代码。

// my objects
var a = {id:101,name:'John Smith',age:42};
var b = {id:102,name:'Greg Jones',age:40};
var c = {id:103, name:'Clyde Barnes',age:36};
var d = {id:104,name:'John Smith',age:51};
var e = {id:105,name:'Sam Owens',age:40};
var f = {id:106, name:'John Smith',age:36};

// stored as an array
var personIndex = [a, b, c, d, e, f];

// my search function - I pass the value from an html form
function searchName(name) {
    'use strict';
    var nameMatch = new Array();
    for(var i = 0; i <  personIndex.length; i++){
        if(name==personIndex[i].name){
            nameMatch.push(i);
        }
    }
    return nameMatch;
}

因此返回值后,我会在下面显示一个带有按钮的列表,并允许用户从多个匹配项中进行选择。所选匹配应将索引值作为cookie传递(我使用警报进行测试):

var y ='';
function displayDetail(value){
    alert(value); // here is where I would pass the value
}

function displayResult(x){
    U.$('results').innerHTML=x;
}

(function(){
    'use strict';
    var cookie = COOKIE.getCookie('nameIndex');
    var c = [];
    c = cookie.split('|');
    for(var i=0;i<c.length;i++){ 
        var x='<br>Id: ' + personindex[c[i]].id + 
            'Name: ' + personindex[c[i]].name + 
            'Age: ' + personindex[c[i]].age + 
            ' <button id=' + c[i] + ' value=' + c[i] + '  onclick=displayDetail(' + c[i] + ')>Details</button>';
        y += x;
    }
    displayResult(y);
})();

这是怎么回事:我搜索约翰史密斯,它显示三个约翰史密斯,每个按钮。我选择第二个,它传递第一个的值。如果我选择第三个,它仍然会传递第一个的值。有人能告诉我我哪里出错吗?

0 个答案:

没有答案