0

我有以下部分完成的代码示例,单击任何表格单元格都会填充第一个input文本框。我想在表格中点击第二次和第三次来填充第二次和第三次输入字段。如果单击第四个文本单元格,它会通过从第一个字段填充等来开始计数。

该功能还有一个小错误,即页面首次加载时,它无法识别第一次鼠标单击。需要第二次单击来填充第一个字段。

提前感谢您帮助我解决这个问题并从中学习。:)

<html>
<head>
    <style>
        td:hover { cursor: hand; color: blue; font-weight: bold; background: #FFDE00; }
    </style>
</head>

<body >

    <p>Click on a cell to have it populate the text fields below<p>

    <table border="1" onclick="populateFields()" style=font-size:11; cellspacing="1" cellpadding="5">
        <tr><td>apple</td><td>orange</td><td>banana</td><td>peach</td></tr>
        <tr><td>tomato</td><td>potato</td><td>onion</td><td>garlic</td></tr>
        <tr><td>chicken</td><td>fish</td><td>beef</td><td>pork</td></tr>
    </table>

    <form>
        <p>The cells you clicked on contain this data:</p>
        <input type="text" name="item1" id="txtCellData"></input>
        <input type="text" name="item2" id="textCellData2"></input>
        <input type="text" name="item3" id="textCellData3"></input>
    </form>

    <script> 
        function populateFields(){
            //put all tds in an array
            var alltds = document.getElementsByTagName("td");

            //go through each item in the array
            for (var i in alltds) {
              alltds[i].onclick = function (){
                txtCellData.value = this.innerHTML;
              }
            }
        }

        function setThis(value) {
            document.getElementById("txtCellData").value = value;
        }
    </script> 

</body>
</html> 
4

1 回答 1

1

为你创造了一个小提琴。看看这段代码

<body onload=populateFields() >

<p>Click on a cell to have it populate the text fields below<p>

<table border="1" onclick="populateFields()" style=font-size:11; cellspacing="1" cellpadding="5">
    <tr><td>apple</td><td>orange</td><td>banana</td><td>peach</td></tr>
    <tr><td>tomato</td><td>potato</td><td>onion</td><td>garlic</td></tr>
    <tr><td>chicken</td><td>fish</td><td>beef</td><td>pork</td></tr>
</table>

<form>
    <p>The cells you clicked on contain this data:</p>
    <input type="text" name="item1" id="txtCellData"></input>
    <input type="text" name="item2" id="textCellData2"></input>
    <input type="text" name="item3" id="textCellData3"></input>
    </form></body>
<script>
var index=0;
function populateFields(){
        //put all tds in an array
        var alltds = document.getElementsByTagName("td");

        //go through each item in the array
        for (var i in alltds) {
          alltds[i].onclick = function (){


             if(index==1){txtCellData.value = this.innerHTML;}
                else{
                    setThis(this.innerHTML);
                    }
          }
        }

        if(index<3){
             index++;
            }else{
                   index = 1;
                  }
            alert(index);

}

    function setThis(value) {
        document.getElementById("textCellData"+index).value = value;
    }

    </script>
于 2013-04-15T21:10:19.990 回答