按下按钮进入输入时获取表格div内容

时间:2016-06-05 10:19:42

标签: javascript jquery html

我想获取每一行的内容并将其写入输入中,但我无法完成这项工作。

<table>
    <tbody>
        <tr>
            <td>
                <div id="a">abc</div>
            </td>
        </tr>
        <tr>
            <td>
                <div id="b">abcd</div>
            </td>            
        </tr>
        <tr>
            <td>
                <div id="c">abcdf</div>
            </td>
        </tr>
        <tr>
            <td>
                <div id="d">abcde</div>
            </td>
        </tr>
        <tr>
            <td>
                <button class="magicButton">choose this row</button>
            </td>
        </tr>
    </tbody>
</table>
$(document).ready(function(){
    $('.magicButton').click(function(){
        // insert text of div a into input
        // insert text of div b into input
        // ect
    });
});

按下按钮后,它会将此值记入以下

<input type="text" name="whatver" div="fromValueA" readonly>
<input type="text" name="whatver" div="fromValueB" readonly>
<input type="text" name="whatver" div="fromValueC" readonly>
<input type="text" name="whatver" div="fromValueD" readonly>

我怎么能得到这个不只是从所有按钮使用相同的A,B,C

祝福,迈克

1 个答案:

答案 0 :(得分:1)

使用jquery replaceWith()方法将div替换为input

$("button").click(function(){
    $("table td > div").replaceWith(function(index, text){
        var id = "fromValue" + $(this).attr("id");
        return "<input id='" + id + "' value='" + text + "' />";
    });
});
table, tr, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <div id="a">A</div>
        </td>
     </tr> 
     <tr>
        <td>
            <div id="b">B</div>
        </td>
     </tr> 
     <tr>
        <td>
            <div id="c">C</div>
        </td>
     </tr> 
     <tr>
        <td>
            <button>Change</button>
        </td>
     </tr> 
</table>