将父<li>内容复制到另一个<ul> onclick吗?

时间:2019-10-23 01:15:14

标签: javascript

在我的网站上,我有两个列表。一个是空的,另一个是一些食谱。我要做的是使用户能够将他喜欢的食谱添加到他的收藏夹中。实际上是通过单击“喜欢”按钮将所选内容复制到空列表中。

HTML

<div id="myrecipes">
   <ul id="recipeList">
   </ul>
</div>

<div id="recipes">
 <ul>
   <li>
     <img src="trpeza.jpg" alt="">
       <p>recipe 1 <i onclick="like(this)" class="fa fa-thumbs-up"></i></p>
   </li>
   <li>
     <img src="trpeza.jpg" alt="">
     <p>recipe 1 <i onclick="like(this)" class="fa fa-thumbs-up"></i></p>
   </li>
 <ul>
</div>

我的JS

function like(x) {
    var emptyList = document.getElementById("recipeList");
    var listItem = x.parentNode;
        x.style.color = "green";
        listItem.appendChild(emptyList);
}

我还想添加一些关闭按钮,以便他可以轻松地将其从收藏夹中删除。

1 个答案:

答案 0 :(得分:0)

在代码段下方尝试此操作

function like(x) {
  var emptyList = document.getElementById("recipeList");
  if (x.classList.contains("fa-thumbs-up")) {
   // For Copying to Favourite Recipes
    var listItem = x.parentNode.parentNode;
    var cln = listItem.cloneNode(true);
    var oAddedIcon = cln.querySelector(".fa-thumbs-up");
    oAddedIcon.classList.remove("fa-thumbs-up");
    oAddedIcon.classList.add("fa-thumbs-down");
    oAddedIcon.style.color = "red";
    x.style.color = "green";
    emptyList.appendChild(cln);
  } else if (x.classList.contains("fa-thumbs-down")) {
  // For deleting from Favourite Recipes
    x.classList.remove("fa-thumbs-down");
    x.classList.add("fa-thumbs-up");
    emptyList.removeChild(x.parentNode.parentNode);

  }

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div id="myrecipes">
  <h2>Favourite Recipes</h2>
  <ul id="recipeList">
  </ul>
</div>
<div id="recipes">
  <h2>Recipes</h2>
  <ul>
    <li>
      <img src="trpeza.jpg" alt="Recipe Image 1">
      <p>recipe 1 <i onclick="like(this)" class="fa fa-thumbs-up"></i></p>
    </li>
    <li>
      <img src="trpeza.jpg" alt="Recipe Image 2">
      <p>recipe 2 <i onclick="like(this)" class="fa fa-thumbs-up"></i></p>
    </li>
    <ul>
</div>