按下按钮替换div中的文本

时间:2014-03-17 09:54:31

标签: jquery html

我有以下项目:http://jsfiddle.net/TXQ9U/40/

我要做的是,当我(" .button2")我被其他内容(包含问题2)取代时。我熟悉.html函数,所以我可以用这个替换内容:

 $(".button2").on("click",function(){
 $("#inner").html('Dit is pagina 2');

 });

但是我不仅想要插入文本,我还希望复制这个(见下文),然后使用新值:

 <p> Question 1: what sport does Roger Federed play? </p>
<table width = "200">

    <tr>
        <td> <input type="radio" name="radio" class="a1" value="a1" /> Cricket </td>
        <td> <input type="radio" name="radio" class="a2" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a3" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a4" value="a1" /> Tennis </td>
    </tr>

</table>

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

尝试这样:

$(".button2").on("click",function(){
    strText = $("#inner").clone(); // clone data
    $('p',strText).html(' Question 2: what sport does Roger Federed play2?');
    $('.a1',strText).text('new value1');//modify cloned data
    $('.a2',strText).text('new value2');
    $('.a3',strText).text('new value3');
    $('.a4',strText).text('new value4');
    $("#inner").html(strText); //set it to show

});

demo

答案 1 :(得分:0)

您可以使用clone

<table width = "200" id="myTable">
<tr>
    <td> <input type="radio" name="radio" class="a1" value="a1" /> Cricket </td>
    <td> <input type="radio" name="radio" class="a2" value="a1" /> Tennis </td>
    <td> <input type="radio" name="radio" class="a3" value="a1" /> Tennis </td>
    <td> <input type="radio" name="radio" class="a4" value="a1" /> Tennis </td>
</tr>
</table>

和你的js:

$(".button2").on("click",function(){
    var clone = $('#myTable').clone();
    $("#inner div").empty().append(clone);
});

注意:你必须像这样编辑你的HTML:

<div id="inner">
<div>
<p> Question 1: what sport does Roger Federed play? </p>
<table width = "200" id="myTable">

    <tr>
        <td> <input type="radio" name="radio" class="a1" value="a1" /> Cricket </td>
        <td> <input type="radio" name="radio" class="a2" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a3" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a4" value="a1" /> Tennis </td>
    </tr>

</table>
    </div>