簡體   English   中英

追加和刪除元素

[英]Append and remove an element

我目前正在使用javascript,html和CSS設計網頁。 該頁面是座位預訂座位,允許用戶選擇和取消選擇座位。 當用戶選擇座位時,我設法使頁面顯示座位的ID,但是如果用戶取消選擇座位,嘗試從顯示中刪除ID時遇到問題。

以下是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()刪除dom元素,而不是屬性。 只需將屬性設置為空字符串即可: $("#list").attr('id', '')

編輯

復習您的問題后,我想我誤會了。 您要刪除顯示ID的文本,而不是實際的id屬性,對嗎?

在這種情況下,最簡單的方法是將文本節點包裝在某種元素中,以使其更易於選擇刪除。

在附加字符串( $("#list").append($(this).attr('id') + "</br>"); )的位置,將輸出包裹成一個跨度,如下所示:

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

這樣,您可以將其刪除為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM