javascript - 如何使用 jquery 将 <li> 附加到点击事件上的另一个 <ol> ?

标签 javascript jquery html jquery-append

我有一个动态生成的列表,这是我的 HTML 代码

<ol class="pending">
  <li><a href="#" class="rendered">One</a></li>
  <li><a href="#" class="rendered">Two</a></li>
  <li><a href="#" class="rendered">Three</a></li>
  <li><a href="#" class="rendered">Four</a></li>
  <li><a href="#" class="rendered">Five</a></li>
  <li><a href="#" class="rendered">Six</a></li>
</ol>
<ol class="patched"></ol>

当单击任何特定链接时,它应该移动到不同的列表。

/*jslint browser: true*/ /*global  $*/ 
$(document).ready(function(){
    "use strict";
    $('.rendered').on('click', function(){
        $(this).toggleClass("rendered patched");
        //$(this).parent().append($(this).wrap("<li></li>"));
        $(this).appendTo("ol.patched");
    });
});

到目前为止,唯一的困难是将

  • 中的 anchor 值作为
  • 添加到新列表中。

    我不断得到的结果是

    <ol class="pending">
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ol> 
    <ol class="moved">
      <a href="#" class="dld">One</a>
      <a href="#" class="dld">Two</a>
      <a href="#" class="dld">Three</a>
      <a href="#" class="dld">Four</a>
      <a href="#" class="dld">Five</a>
      <a href="#" class="dld">Six</a>
    </ol>
    

    我不确定我对 .append().appendTo() 有何误解

  • 最佳答案

    您应该选择 anchor 的父级并将其附加到ol。 jQuery .parent()选择元素的父元素。

    $('.rendered').on('click', function(){
        $(this).toggleClass("rendered patched");
        $(this).parent().appendTo("ol.patched");
    });
    

    $('.rendered').on('click', function(){
      $(this).toggleClass("rendered patched");
      $(this).parent().appendTo("ol.patched");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ol class="pending">
      <li><a href="#" class="rendered">One</a></li>
      <li><a href="#" class="rendered">Two</a></li>
      <li><a href="#" class="rendered">Three</a></li>
      <li><a href="#" class="rendered">Four</a></li>
      <li><a href="#" class="rendered">Five</a></li>
      <li><a href="#" class="rendered">Six</a></li>
    </ol>
    <ol class="patched"></ol>

    您也可以在一行中编写代码

    $('.rendered').on('click', function(){
      $(this).toggleClass("rendered patched").parent().appendTo("ol.patched");
    });
    

    关于javascript - 如何使用 jquery 将 <li> 附加到点击事件上的另一个 <ol> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41177595/

    相关文章:

    javascript - React.js + Reactstrap 一个组件中的多个模态

    jquery - 使用 JQuery 在 DIV 中显示繁忙指示器

    javascript - 多个下拉菜单滑动切换

    javascript - 只关注第一个元素

    javascript - 在文档中放置 JavaScript/Ajax 的最佳位置在哪里?

    javascript - 在网页中绘制单词之间的链接

    javascript - 我是否错误地使用了 GraphQL?我不知道它如何向我发送回数据

    javascript - 天文坐标转换错误

    javascript - 将 youtube 视频 url 转换为嵌入代码

    html - css text-decoration 下划线在应用于输入按钮的文本时不起作用