【问题标题】:Jquery - cloning a paragraph with no IdJquery - 克隆没有ID的段落
【发布时间】:2014-03-02 15:52:44
【问题描述】:
<div id="note"></div>
<p>
Item 1 
<input name="one" type="checkbox" value="Item 1" />
</p> 
<p>
Item 2 
<input name="two" type="checkbox" value="Item 2" />
</p> 
<p>
Item 3 
<input name="anything" type="checkbox" value="Item 3" />
</p> 
<br/>
Current issue: Does not work as expected. We want to duplicate the paragraph containing the input field whenever it is clicked (involving updating the name). Constraint - Original html cannot be changed.

脚本(在这篇文章的帮助下)

var plen;
$(document).on('click', 'input[type="checkbox"]', function(){
plen = $('p').length
$(this).parent().clone(true).appendTo('body').attr('id',''+plen)
$(this).prop('checked', true);
//alert(plen)
$('#note').text('More of item '+ plen)
});

我快到了,但距离理想的结果还很远。在 JSFiddle 中解释。

JSFiddle 在这里:http://jsfiddle.net/Sergelie/ULywc/

【问题讨论】:

    标签: jquery dynamic cloning


    【解决方案1】:

    是的,我们可以克隆选中的父 p 标签。下面是示例代码。

    HTML

    <div id="note"></div>
    <p>
    Item 1 
    <input name="one" type="radio" value="Item 1" />
    </p>    
    

    jQuery 代码

    var plen;
    $(document).on('change', 'input[type="radio"]', function(){
        plen = $('p').length
        $(this).parent().clone(true).appendTo('body').attr('id','one'+plen)
        $(this).prop('checked', true);
        //alert(plen)
        $('#note').text('More of item '+ plen)
    });
    

    Demo

    【讨论】:

    • link Rakesh,谢谢,我们正在路上!我创建了更接近真实情况的 jsfiddle。 1)如果我们需要一个div,它必须是动态创建的,并且定位在clone之上。 2)该事件应该只在选中该框时发生,如果未选中该框(理想!),则该事件将被销毁
    • jsfiddle.net/Sergelie/ULywc/1 - 我们现在在哪里,我在小提琴中添加了一些 cmets。拉德什。
    • @user3371049 请用正确的描述更新问题,而不是在答案下方评论新要求...
    猜你喜欢
    • 2010-09-29
    • 2011-12-22
    • 2016-07-02
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多