有没有办法在运行时使用jquery克隆硬编码元素或元素集?

时间:2010-12-09 18:54:09

标签: javascript jquery

我需要知道如何在运行时克隆硬编码元素?

我有一个硬编码输入字段。在运行时,可以读取该元素并使其按用户请求多次(追加)。这可能与jquery或javascript。

提前致谢。

3 个答案:

答案 0 :(得分:1)

“硬编码”是什么意思?这就是你需要的吗?

$(document).ready(function () {
    $("#something").click(function(){
        $("#yourform").append($("#yourinputfield"))  
    });
})

答案 1 :(得分:1)

使用jQuery clone:

    <div class="smallBox">
        I'm a small box
        <div class="smallInnerBox">I'm a small small inner box</div>
    </div>

    $('.smallBox').clone().insertAfter(".smallBox");

    <div class="smallBox">
        I'm a small box
        <div class="smallInnerBox">I'm a small small inner box</div>
    </div>
    <div class="smallBox">
        I'm a small box
        <div class="smallInnerBox">I'm a small small inner box</div>
    </div>

如果你正在寻找更全面的东西:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
    <ul id='itemList'>
        <li>
            <input class='input' type="text" value="some text"/>
            <a class='clone' href='Javascript:;'>Clone</a>
        </li>
    </ul>
    <a id='allValues' href='Javascript:;'>Get Values</a>
<script>
    $('a.clone').live('click', function() {
        var clonedItem = $(this).parent().clone();
        clonedItem.find('.input').attr('value', 'cloned');
        $('#itemList').append(clonedItem);
    });

    $('#allValues').click(function(){
        var values = [];
        $('.input').each(function(i, text){
            values[i] = $(text).val();
        });
        alert('Values are: ' + values.join(', '));
    });
</script>
</body>
</html>

答案 2 :(得分:0)

<div id="divElement">Hello</div>
<button onclick="javascript:cloneElement()">Clone Me</button>


function cloneElement()
{
    $("#divElement").clone().appendTo("#divElement");
}

或者:http://jsfiddle.net/UFcTk/