我有一个动态生成的列表,这是我的 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");
});
});
到目前为止,唯一的困难是将
我不断得到的结果是
<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/