Получение значения параметра из таблицы с использованием Javascript - PullRequest
0 голосов
/ 24 мая 2010

Я хочу получать параметр в моей таблице (HTLML) каждый раз, когда пользователь нажимает кнопку редактирования. Таблица содержит в каждой строке кнопку редактирования, например:

 retour.append("<td>");

                           retour.append("<button  id=edit name=edit type=button  onClick= editarow()>");
                           retour.append("<img src=edit.gif />");
                           retour.append("</button>");
                           retour.append("</td>");

, чтобы получить значение каждой строки, где щелкают по редактированию с использованием JavaScript, я делаю следующее:

function  editarow(){
var table = document.getElementById("sheet");
    var buttons = table.getElementsByTagName("button");
       for(var i=0; i<buttons.length; i++) {
        if(buttons[i].name=="edit") {
            buttons[i].onclick = function() 
                {
                var buttonCell = this.parentNode; //cell
                var editThisRow = buttonCell.parentNode; //td
                var er=editThisRow.parentNode.attributes[1].value;
                alert(er);
                }

        }
      }

}

но я не получил ожидаемых значений.

Ответы [ 2 ]

1 голос
/ 24 мая 2010

У вас есть ошибка в элементе button, это:

onClick= editarow()

должно быть

onclick='editarow()'

("C" должен быть в нижнем регистре, а вызов функции в кавычках.)

Давайте предположим, что строка выглядит следующим образом:

<tr>
    <td data-foo="bar">John</td>
    <td>Doe</td>
    <td>...your edit button...</td>
</tr>

В editarow вы можете сделать это:

function editarow() {
    var row, firstNameCell, lastNameCell;

    // `this` is the button, so `this.parentNode` is the cell, and
    // `this.parentNode.parentNode` is the row
    row = this.parentNode.parentNode;

    // The first name cell is the first child
    firstNameCell = findElement(row.firstChild);

    // The second name cell is its next sibling
    lastNameCell = findElement(firstNameCell.nextSibling);

    // Their "values" are the text within them, most easily accessed via
    // `innerHTML`
    alert("First name is " + firstNameCell.innerHTML);
    alert("Last name is " + lastNameCell.innerHTML);

    // Or if you store data in attributes, you can get them via
    // `getAttribute`
    alert("data-foo = " + firstNameCell.getAttribute("data-foo"));
}

function findElement(node) {
    while (node && node.nodeType != 1) {
        node = node.nextSibling;
    }
    return node;
}

Все становится намного проще, если вы используете jQuery , Прототип , Закрытие или другие библиотеки . (Например, вышеприведенная функция findElement очень грубая; ее цель - пропустить текстовые узлы и тому подобное.)

0 голосов
/ 24 мая 2010

так что это решается так:

function editarow() {
    var row, firstNameCell, lastNameCell;
    var table = document.getElementById("sheet");
    var buttons = table.getElementsByTagName("button");
    for(var i=0; i<buttons.length; i++) {
        if(buttons[i].name=="edit") {
            buttons[i].onclick = function() 
                {
       row = this.parentNode.parentNode;

    // The first name cell is the first child
    NameCell1 = findElement(row.firstChild);
    NameCell2 = findElement(NameCell1.nextSibling);
    NameCell3=findElement(NameCell2.nextSibling);
    NameCell4=findElement(NameCell3.nextSibling);
    NameCell5=findElement(NameCell4.nextSibling);
    NameCell6=findElement(NameCell5.nextSibling);
    NameCell7=findElement(NameCell6.nextSibling);

    // `innerHTML` pour obtenir la valeur
    alert("name 1  is " + NameCell1.innerHTML);
    alert("name 2  is " + NameCell2.innerHTML);
    alert("name 3  is " + NameCell3.innerHTML);
    alert("name 4  is " + NameCell4.innerHTML);
    alert("name 5  is " + NameCell5.innerHTML);
    alert("name 6  is " + NameCell6.innerHTML);
    alert("name 7 is " + NameCell7.innerHTML);

}
        }}
        }

function findElement(node) {
    while (node && node.nodeType != 1) {
        node = node.nextSibling;
    }
    return node;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...