簡體   English   中英

使用 jQuery 創建列表項后如何修改它?

[英]How can I modify a list item after I created it with jQuery?

這是我做的待辦事項清單。 (為了使我的代碼更具可讀性,我嘗試發表評論。我希望它有效。)

如果您嘗試我的演示,您可以使用“添加”按鈕添加 li 項目。 li 項目還有 2 個按鈕。 我想為可以修改列表項的用戶創建一個修改按鈕。 我不知道我能用 jQuery 做什么。

第二個問題是列表按鈕不能很好地工作。 因為如果我使用一次刪除按鈕,它會更改完成按鈕以刪除項目。 但是,如果我不使用刪除按鈕,則完成按鈕運行良好。 我不知道為什么,也許相同的 class 名稱是問題所在?

這是我在 JS Bin 中的演示: https://jsbin.com/natiziqawa/edit?html,js,output

   $(document).ready(function(){
     $("#add").click(function(){

 // Created list elements and their's buttons
    var list_item =document.createElement("li");
      var remove_button=document.createElement("button");
      var done_button=document.createElement("button");
     


 // append the buttons some string to caption buttons
   

   $(remove_button).append("Delete");
   $(done_button).append("Done");


   


 
 // added class name the items to to distinguish them 

  $(list_item).addClass("item")
  $(remove_button).addClass("delete"); 
  $(done_button).addClass("done"); 
  



 // filled  the created items with the input values
 
 var list_text =$("#input").val();
 var time=$("#time").val();
 
 
 // filled the list item with their's  buttons and class names and input values

 $(list_item).append(time,"   :   ",list_text,done_button,remove_button); 

 // finally fill the ul with list items but first check out what is written in the input


 if(input.value==""){
   alert("Please enter an activity")
 
  }


  // If the input has some value  can go 

  else{
 $("ul").append(list_item);

 // after clicked, clear the input field
 $("#input").val("");
 
  


// list item's buttons


$(".done").click(function(){

  $(list_item).click(function(){
    $(this).css("color","white")
    $(this).css("text-decoration","line-through")
  }); 
});





$(".delete").click(function(){
    $(list_item).click(function(){
      $(this).remove()
    }); 
  });

}

  });// main function close
  
}); // document ready close

我的解決方案背后的想法是對添加的字段使用contenteditable屬性。 為此,您需要將前兩個字段動態包裝在一個額外的 div 中,如下所示:

$(list_item).append('<div class="edit_item" contenteditable="true">'+time+'</div>',"   :   ",'<div class="edit_item" contenteditable="true">'+list_text+'</div>',done_button,remove_button); 

您需要將此代碼替換為現有代碼。 為了更好地理解,此代碼位於注釋中: “// 用他們的按鈕和 class 名稱和輸入值填充列表項”

此外,您需要將此規則添加到 css 以對齊字段:

.edit_item {
  display: inline-block;
}

關於第二個問題:

您遇到了定位問題。 您必須使用closest()方法引用當前的list_item

對於標記:

$(".done").click(function(){
   $(this).closest(list_item).css("color","white")
   $(this).closest(list_item).css("text-decoration","line-through");
});

對於刪除:

$(".delete").click(function(){
   $(this).closest(list_item).remove();
});

暫無
暫無

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

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