简体   繁体   English

将Div类附加到超链接类-然后在单击时将超链接克隆并附加到容器

[英]Append Div Class to Hyperlink Class — then Clone & Append Hyperlink To Container on Click

  1. I want to append a div class ('.link-cloner') to a hyperlink class ('.link') when you hover over any hyperlink (that has the '.link' class). 当您将鼠标悬停在任何超链接(具有“ .link”类)上时,我想将div类(“ .link-cloner”)附加到超链接类(“ .link”)上。
  2. Then when you click on the appended (.link-cloner) class, I want to clone the hyperlink it was appended to, and append that (link) to #container. 然后,当您单击附加的(.link-cloner)类时,我要克隆附加到该超链接的超链接,然后将该(链接)附加到#container。

I'm almost there, I just can't make the last part work. 我快到了,我无法使最后一部分正常工作。

Codepen: http://codepen.io/StrengthandFreedom/pen/JXEEQP/ Codepen: http ://codepen.io/StrengthandFreedom/pen/JXEEQP/

I tried using find(), closest() & $(this) in various combinations, but I can't make it just clone the hyperlink (not the linkCloner) and append it to the #container. 我尝试以各种组合使用find(),最近的()和$(this),但是我不能使其仅克隆超链接(而不是linkCloner)并将其附加到#container。

jQuery: jQuery的:

$(document).ready(function(e) {
  /* ------------------------
    Part 1 — WORKS
  --------------------------*/
  // Store link-cloner div in variable
  var linkCloner = $('<div class="link-cloner">Cloner</div>');

  // When mouse hover over any hyperlink
  $('.link').on('mouseover', function() {

    // Append the link-cloner class to the hyperlink
    $(this).append(linkCloner);
  }).mouseleave(function() {

    //on mouse leave, remove link-cloner 
    $(linkCloner).remove();
  });
/* ------------------------
    Part 2 — DOESN'T WORK
  --------------------------*/
  //Then when you click on the appended linkCloner, 
  clone the hyperlink and append it to the #container
  $(linkCloner).on('click', function() {

  // This code is wrong.... 
  event.preventDefault();
  $('.link').clone().append('<li></li>').appendTo('#container');

  });
});

Can someone lead me in the right direction? 有人可以指引我正确的方向吗? JavaScript or jQuery, either is fine by me (I'm learning both) :-) JavaScript或jQuery,对我来说都很好(我都在学习):-)

You have done just small mistake. 您犯了一个小错误。 Replace your PART 2 with below code : 将您的PART 2替换为以下代码:

$('.link').on('click', function(event) {

  // This code is wrong.... 
  event.preventDefault();
  $(this).clone().append('<li></li>').appendTo('#container');

});

Try to use 尝试使用

$().drag();

for the clone that link to div check jquery documentations 对于链接到div的克隆,请检查jquery文档

Hope Help 希望帮助

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

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