简体   繁体   English

我如何克隆和删除jQuery的最后一个孩子?

[英]How do I clone and remove last child with jquery?

I want to clone and remove ul last-child but following code is not working. 我想克隆并删除ul最后一个孩子,但以下代码不起作用。 Someone tell me how it will be work? 有人告诉我它将如何工作?

$(document).ready(function () {
    tmp1 = '';
    tmp = '<ul><li><h4>Menu 5</h4></li></ul><ul><li><h4>Menu 6</h4></li></ul><ul><li><h4>Menu 7</h4></li></ul>';
    $(tmp).children('ul:last-child').clone().appendTo(tmp1)
    $(tmp).children('ul:last').remove();
    $('div').append(tmp);
});

I think you are doing it wrong: tmp is a string. 我认为您做错了: tmp是一个字符串。

You have to do this: http://jsfiddle.net/Lu6jA/ 您必须这样做: http : //jsfiddle.net/Lu6jA/

$(document).ready(function () {
   tmp1 = '';
   tmp = '<ul><li><h4>Menu 5</h4></li></ul><ul><li><h4>Menu 6</h4></li></ul><ul><li><h4>Menu 7</h4></li></ul>';
   var lastUl = tmp.lastIndexOf("<ul>");
   var yourclone = tmp.substring(lastUl);
   var newtmp = tmp.replace(yourclone,"");
   $('div').append(newtmp);
   alert(yourclone);  // This is for your reference
});

Explantion: First find the last UL from the string. 外植体:首先从字符串中找到last UL yourclone contains your last ul as a string. yourclone包含您的最后一个ul作为字符串。 Now, replace last ul from the tmp string with nothing, so basically means remove it and place the result in newtmp . 现在,将tmp字符串中的last ul替换为newtmp ,因此基本上意味着将其删除并将结果放在newtmp the append it to div . 将其附加到div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM