简体   繁体   English

追加和删除元素

[英]Append and remove an element

I am currently designing a web page using javascript, html and css. 我目前正在使用javascript,html和CSS设计网页。 The page is a seat booking seat which allows the user to select and unselect seats. 该页面是座位预订座位,允许用户选择和取消选择座位。 I have managed to get the page to display id of the seat when the user have selected a seat, but I am having problems trying to remove id from the display if user unselects the seat. 当用户选择座位时,我设法使页面显示座位的ID,但是如果用户取消选择座位,尝试从显示中删除ID时遇到问题。

Below is the javascript code 以下是JavaScript代码

    $('.available, .unavailable, .selected').click(function(){
        var ID = $(this).attr('class');
        if (ID == 'n unavailable' || ID == 'p unavailable') {
            alert ('Seat is already booked. Please select another seat.');
        }
        else if (ID == 'n selected' || ID == 'p selected') {
            alert ('You have now unselected this seat.');
            $(this).html('<img src = "free.gif"/>');
            $(this).removeClass('selected').addClass('available');
            y--;
            $("#seats").html("Number of seats selected: " + y);
            $("#list").remove($(this).attr('id'));
        }
        else {
            alert ('You have now reserved this seat. You can unselect it by clicking the seat again.');
            $(this).html('<img src = "selected.gif"/>');
            $(this).removeClass('available').addClass('selected');
            y++;
            $("#seats").html("Number of seats selected: " + y);
            $("#list").append($(this).attr('id') + "</br>");
        }
    });

remove() removes a dom element, not an attribute. remove()删除dom元素,而不是属性。 Just set the attribute to an empty string: $("#list").attr('id', '') 只需将属性设置为空字符串即可: $("#list").attr('id', '')

edit 编辑

After reviewing your question, I think I misunderstood. 复习您的问题后,我想我误会了。 You want to remove the text which displays the ID, not the actual id attribute, correct? 您要删除显示ID的文本,而不是实际的id属性,对吗?

In this case, the easiest thing would be to wrap the text node in some sort of element, to make it easier to select for removal. 在这种情况下,最简单的方法是将文本节点包装在某种元素中,以使其更易于选择删除。

Where you append the string ( $("#list").append($(this).attr('id') + "</br>"); ), wrap the output in a span like so: 在附加字符串( $("#list").append($(this).attr('id') + "</br>"); )的位置,将输出包裹成一个跨度,如下所示:

$("#list").append('<div class="id">' + $(this).attr('id') + "</div>");

This way, you can remove it as such: 这样,您可以将其删除为:

$('#list').remove('#id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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