开发者

clone is not working properly

开发者 https://www.devze.com 2023-04-12 09:09 出处:网络
I am trying this code, but apparently i have some bug. The problem is here, because without this part all works correctly:

I am trying this code, but apparently i have some bug.

The problem is here, because without this part all works correctly:

        .find('ol:first >li:eq(0)')
        .attr('id', 'one' + increment)
        .find('ol:first >li:eq(1)')
        .attr('id', 'two' + increment)

full source:

<div id="container">
<div id="input0" class="clonedInput">
<br>
    <ol id="vall0">
    <li id="one0">one</li>
    <li id="two0">two</li>
    </ol>
<input id="value0" size="20" type="text"/>
</div>
</div>

    <script type="text/javascript">
      $(document).ready(function() {
    var $container = $('#container'),

        $clone = $('#input0'),

        numClones = 4,

        startNumber = 1;

    function cloneInput(num, increment, $elem) {
        var $newElem = $elem
        .clone(true)
        .attr('id', 'input' + increment)
        .find('ol:first')
        .attr('id', 'vall' + increment)
        .find('ol:first >li:eq(0)')
        .attr('id', 'one' + increment)
        .find('ol:first >li:eq(1)')
        .attr('id', 'two' + increment)
        .end();

        $newElem.children(':text')
        .prop('id', "value" + increment)
        .prop('valor', 'valor')
        .val('');


        $container.append($newElem);

        if (num > 1) {
            var next = n开发者_JAVA百科um - 1;
            var incr = increment + 1;
            cloneInput(next, incr, $elem);
        }
    }

    cloneInput(numClones, startNumber, $clone);
    });
        </script>

demo


One possible solution is to change your problem part to:

.find('>li:eq(0)')
.attr('id', 'one' + increment)
.end()
.find('>li:eq(1)')
.attr('id', 'two' + increment)
.end()

Also see my jsfiddle.


.end() may not be doing what you think it does.

You don't need to call it at the end of a chain of jQuery calls like that.

What .end() does is that it will effectively "pop" you back to the previous filter result/scope. Subsequent calls to .find() will perform the selection on top of the currently filtered elements. Toy around with adding .end() calls before making additional .find() calls:

    .clone(true)
    .attr('id', 'input' + increment).end()
    .find('ol:first')
    .attr('id', 'vall' + increment).end()
    .find('ol:first >li:eq(0)')
    .attr('id', 'one' + increment).end()
    .find('ol:first >li:eq(1)')
    .attr('id', 'two' + increment).end()

However, I must say that you're not making the most efficient use of jQuery selectors...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号