单击获取有关JS构造按钮的信息

时间:2016-07-18 07:38:48

标签: javascript html

是否可以获取由javascript循环创建的按钮的信息,例如id,value?例如,下面的代码为由对象数组形成的表中的每一行创建一个按钮?

    var table = document.createElement("TABLE");
    table.setAttribute("id", "tableOfArray");

    var array = [ (a large array of objects here) ];
    for (var i = 0; i < array.length; i++)
    {
        row = table.insertRow(i);
        cell1 = row.insertCell(0);
        cell2 = row.insertCell(1);
        cell3 = row.insertCell(2);
        cell4 = row.insertCell(3);
        cell5 = row.insertCell(4);
        cell6 = row.insertCell(5);

        cell1.innerHTML = i + 1;    //for numbering the table       
        cell2.innerHTML = array[i].property1;
        cell3.innerHTML = array[i].property2;
        cell4.innerHTML = array[i].property3;
        cell5.innerHTML = array[i].property4;

        var button = document.createElement("BUTTON");
        var buttonText = document.createTextNode("Remove Line");
        button.appendChild(buttonText);

        button.setAttribute("id", String(i));
        button.setAttribute("value", String(i));
        button.setAttribute("onClick", "remove()");

        cell6.appendChild(button);
    }

    function remove()
    {
        ?? //gets the value of the button that was pressed
        var buttonValue = ??; //assigns the value of button to the variable
        arrayTable = document.getElementById("tableOfArray");

        table.deleteRow(buttonValue);
    }

是否有一种方法可用于获取按钮的ID或值以执行删除操作?

1 个答案:

答案 0 :(得分:0)

您可以传递this

来传递当前上下文
button.setAttribute("onClick", "remove(this.id)");
function remove(id){
 var _id=id;// id of the button;
}

否则你可以使用事件对象

function remove(event){
 var _target = event.target;
  var _getId = _target.id;
 var _getParentTD = _target.parentElement; // will give the td which contain button
var _getParentTR = _target.parentElement.parentElement; // will return tr
}