簡體   English   中英

如何刪除使用按鈕創建的內容

[英]How can I remove the contents I create with my button

關於另一個問題,我在這里是JQuery的新手。我有一個任務,創建一個簡單的JQuery,以選擇日期,鍵入事件並將其添加到列表中,每個列表前面都有一個紅色的小按鈕。項目。

我的代碼如下:

<!doctype html>
<html lang="en">
     <head>
      <meta charset="utf-8">
      <title>jQuery UI Datepicker - Display month &amp; year menus</title>
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

      <link rel="stylesheet" href="css.css">

      <script>
      $(function() {
        $( "#datepicker" ).datepicker({
          changeMonth: true,
          changeYear: true
        });
      });

      $(document).on('click', '#bta', function () {

        if ($('#datepicker').val() != '' && $('#evento').val() != '' ) {
           $('#caixa').prepend('<p>' + $('#datepicker').val() + '&nbsp;' + $('#evento').val() + '&nbsp;' + '<input type="button" id="apagar" class="apagar" value="apagar"/>' + '</p>');
            $('input').val('');
        }

    });

     $(document).on('click', '#apagar', function () {
       $( "p" ).remove();
       });

      </script>
    </head>

    <body>
        <div id="box">
            Lista de Tarefas:
            <br><br>
            Date: <input type="text" id="datepicker"> &nbsp; &nbsp;

            Event: <input type="text" id="evento">    <button id="bta" class="bta">+</button>

            <div id="caixa">  </div>
            </body>
        </div>

</html>

我遇到的問題非常簡單,我創建的紅色按鈕應該擦除我創建的整行以及僅特定行,問題是紅色按鈕擦除了列表中我擁有的每個內容。

我知道這是因為它們都具有段落標簽,但是如何使按鈕僅擦除一行呢?

這是我今天要問的第二個問題,我通常不這樣做,但這大概是2-3天,但是到了空閑時間,我接下來的幾天是無法預測的,所以這就是為什么我今天要問第二個問題...

提前致謝。

不能刪除所有“ p”,而只能刪除最接近的“ p”。

更改此行:

   $( "p" ).remove();

有了這個:

   $(this).closest("p").remove();

這里有一個完整的示例: http : //jsbin.com/gikululofu/edit?html,輸出

在給出解決方案之前,讓我指出腳本中的一個小錯誤。

單擊按鈕apagar相同的ID添加到動態按鈕bta 現有代碼將起作用,因為您將事件委派用於動態按鈕單擊事件,但這不是正確的方法,即使它起作用( DOM中的元素永遠不要具有相同的ID )。 我建議使用動態按鈕類 (您已經在做),並在事件委托選擇器中將此類用於click事件。 因此,刪除ID后,動態按鈕的代碼應如下所示。

<input type="button" class="apagar" value="apagar"/>'

現在的解決方案是在clicked元素上使用Jquery的mostest ()功能。 由於單擊該按鈕后該按鈕包裹在p標簽內,因此讓我們使用closest的方法找到p標簽,該標簽會冒泡直到找到元素然后刪除p標簽。 因此,更改您的腳本,該腳本應將p標簽刪除到下面。

$(document).on('click', '.apagar', function () { // changed id selector to class $(this).closest( "p" ).remove(); // access particular p tag and remove });

暫無
暫無

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

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