简体   繁体   中英

Removing <p> element with jQuery

This is a jQuery function that determines the class of an image within a table and acts accordingly. If the image parent doesn't have the class selected , it gives it that class and then adds the td id to a div (order). If it does have the class selected , it should remove the class, which it does, and then remove the p element containing the td id .

$(document).ready(function () {
    $('td img').click(function () {
        if ($(this).parent().hasClass('x')) {
            alert("Seat " + ($(this).parent().attr("id")) + " is taken");
        } else if ($(this).parent().hasClass('selected')) {
            $(this).attr('src', 'images/a.gif');
            $(this).parent().removeClass('selected');
            var z = $(this).parent().attr('id');
            $(z).remove();
            return false;
        } else {
            $(this).attr('src', 'images/c.gif');
            $(this).parent().addClass('selected');
            alert($(this).parent().attr("class"));
            var z = $(this).parent().attr('id');
            $('<p>').attr('id', z).text(z).appendTo('#order');
            return false;
        };
    });
});

It works up until removing the p element, where it just doesn't. The p id is dynamically set and is the same as the td id , hence the use of a variable to choose the id.

Ok, so it was a combination of answers on here.

Firstly, the ids weren't unique, so I added a suffix to them:

var z = $(this).parent().attr('id'); $('<p>').attr('id', z+'1' ).text(z).appendTo('#order');'

Then used the suggestion of $('#' + z).remove(); but changed it for my new suffix, so it now shows this $('#' + z+'1').remove();

All seems to be working now, thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM