开发者

jQuery - Can't remove an appended div

开发者 https://www.devze.com 2023-01-22 13:24 出处:网络
Hey All, thanks for the help in advance. I\'m trying to create 开发者_开发百科and remove input fields dynamically, they create just fine, but when i try to remove them it doesn\'t seem to find the div

Hey All, thanks for the help in advance. I'm trying to create 开发者_开发百科and remove input fields dynamically, they create just fine, but when i try to remove them it doesn't seem to find the div thats created, and removes the div above it, and hence all the inputs, instead of the just the one.

Heres my jscript:

$("#addp").live('click' ,(function() {
    var partid = $('#partlist').val();
    var partname = $("#partlist option:selected").text();
    $('<div>').appendTo('#parts');
    $('<label for="parts" class="left">' + partname + ': </label>').appendTo('#parts'); 
    $('<input type="text" name="part[' + partid + ']">').appendTo('#parts');
    $('<input type="button" class="removepart" value="X">').appendTo('#parts');
    $('</div">').appendTo('#parts');
    numparts++;
})); 

$(".removepart").live('click', (function () {
    $(this).closest('div').remove();
}));

and HTML

<p class="edit">Parts Used</p>
<label for="parts" class="blank">Search for a Part</label>
<input type="text" name="partsearch" id="searchp_box" /> 
<input type="button" id="searchp_button" name="search" value="Search">
<br/>
<label for="parts" class="blank">Parts Used</label>
<select name="parts" id="partlist">
</select>
<input type="button" name="search" id="addp" value="Add Part">
<br>
<div id="parts">
</div>

It should removes the closest div, which is created when you press the add button, but instead it removes the whole div id="parts" .

I searched around and was told to use .live, but it didn't seem to work :(

Thanks for reading :)


When jquery appends (or appendTo's) it will try and create the DOM element, meaning this line:

$('<div>').appendTo('#parts');

Makes this html:

<div id="parts">
<div></div>
</div>

So everything after that line is not inside your new DIV at all, it keeps getting added afterwards. You can verify in FF/Firebug Chrome/Inspect Element IE/Developer Tools.

What i'd do is make your new part into a string, then append that string:

    $("#addp").live('click' ,(function() {
        var partid = $('#partlist').val();
        var partname = $("#partlist option:selected").text();
        var newPart = '<div> \
                       <label for="parts" class="left">' 
                       + partname + ': </label> \
                       <input type="text" name="part[' + partid + ']"> \
                       <input type="button" class="removepart" value="X"> \
                       </div>';
        $(newPart).appendTo('#parts');
        numparts++;
    })); 

$(".removepart").live('click', (function () {
    $(this).closest('div').remove();
}));
0

精彩评论

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

关注公众号