开发者

jquery clone div then find and replace everywhere

开发者 https://www.devze.com 2023-04-12 22:08 出处:网络
EDIT I tried both of the suggestions below, but it\'s still not working... It clones, but doesn\'t increment...

EDIT I tried both of the suggestions below, but it's still not working... It clones, but doesn't increment...

function createNewSection() {

var cloneUp = $('.section-form').length;
var cloneCount = $('.section-form').length - 1;

var newSection = $('#section-0').clone(function() {
        $(this).find('*').each(function() {
            $(this).attr('id', $('#section-0').attr('id').replace(/section-0/,'section-'+cloneUp).replace(/section[_\[]0\]?/,'section_'+cloneUp));
            $(this).attr('name', $('#section-0').attr('replac开发者_运维知识库e').replace(/section-0/,'section-'+cloneUp).replace(/section[_\[]0\]?/,'section_'+cloneUp));
        });
});




$('#sections').append(newSection);

}

I'm trying to replace all instances of a particular string and have tried a number of ways to do it, but more often than not, I get an error saying replace isn't a function, $(this) is undefined, or missing : after argument...

For example, in the following HTML:

<div id="section-1-add">
    <div id="section-1">
      <span class="section_1-span">Title</span>

       <input name="section[1][item][62]" id="section-1-item-1" value="Enter Section 1 / Item 1" />

    </div>
</div>

I want to replace all instances of:

section-1 with section-2
section_1 with section_2
section[1] with section_2

I've tried many variations of essentially the same thing, but here is the most recent attempt:

function createNewSection() {

    var cloneUp = 2;  //this is currently hardcoded, but will be dynamic... just for this example

    var newSection = $('#section-1-add').clone(function() {
            $(this).find('*').each(function() {
                $(this).id=$(this).id.replace(/section-1/,'section-'+cloneUp).replace(/section[_\[]1\]?/,'section_'+cloneUp);
                $(this).name=$(this).name.replace(/section-1/,'section-'+cloneUp).replace(/section[_\[]1\]?/,'section_'+cloneUp);
            });
    });

    $('#sections').append(newSection);
}

In the code above, the section is cloned, but none of the ids or names change...


You should use .attr() function to get and replace id, class value. For example:

$('#section-1').attr('id', $('#section-1').attr('id').replace(/section-1/g, 'section_1'));


The following code:

 $(this)

identifies a jQuery Object, but it looks as if you want to modify the actual DOM object. To get that DOM object, try...

 $(this)[0].id = $(this)[0].id.replace(/*etc*/);
0

精彩评论

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

关注公众号