jquery cloning html problem, update DOM?

2019-05-23 03:26发布

问题:

I need help of javascript / jquery experts to solve the next problem:

---- 1. this javascript alerts the id of a selected option in a select html tag:

$(function(){
    $("#id_productos_list").change(
    function(){
        var op = $(this).selectedValues()
        alert(op);
     }
     );
});

----2. this javascript clone html code:

function cloneMore(selector, type) {
    var newElement = $(selector).clone();
    var total = $('#id_' + type + '-TOTAL_FORMS').val();

    newElement.find(':input').each(function() {
        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
    });
    newElement.find('label').each(function() {
        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
        $(this).attr('for', newFor);
    });

    total++;
    $('#id_' + type + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);
}

---- this is a part of the HTML code that JS is cloning, and it works with no problems

            <select id="id_productos_list" name="productos_list" >
              <option value="1">One</option>
              <option value="2">Two</option>
            </select>

BUT just the javascript #1 works with the initial html code (original for clone). the cloned others doesnt alert selected options. I've tested with diferents id's attrs for each cloned select tags, without results.

What im missing? firebug display the cloned html DOM nice :S Do I have to update DOM after cloning to make $("#id productos list").change(...) works?

回答1:

The jQuery $("#...") syntax will return the first matched element by exact id. If you are cloning elements but not differentiating them by their id, this code will not work as you expect it to.

You can compare the differences between the following two expressions:

alert($("#id_productos_list").size());

...and

alert($("[id='#id_productos_list']").size());

The first expression will return either zero or one depending on the presence of an element with id "id_productos_list" in your page. The first element in declared order wins.

The second expression will return zero or one or more depending on the the set of all elements with id "id_productos_list" in your page.

Also important to note is that it doesn't appear that the event handlers are copied over as part of the clone() operation. You may need to reassign these handlers to the new elements.

var newElement = $(selector).clone(true);


回答2:

Have you tried .clone(true) which clones all the handlers attached? It's described at the bottom of the Clone documentation.