Javascript 在同一上下文中复制同一事物
我对jquery有一个问题,我有两组不同的图标,每一个图标我都想要相同的东西: 我的主要代码是Javascript 在同一上下文中复制同一事物,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我对jquery有一个问题,我有两组不同的图标,每一个图标我都想要相同的东西: 我的主要代码是 但结果是浏览器挂起:“(您需要克隆元素并将其添加到当前a var socials = $("ul a"); socials.each(function (index, elem) { var jumpIcons = $(this).find("i"); //first you need to clone the current element else, you are just re
但结果是浏览器挂起:“(您需要克隆元素并将其添加到当前
a
var socials = $("ul a");
socials.each(function (index, elem) {
var jumpIcons = $(this).find("i");
//first you need to clone the current element else, you are just repositioning the current `i` elemnet
//then you need to append it to the current a element, not to all `a` element in the socials - this will cause a lot of iteration if there a lot of `ul a` elements in the page resulting in unresponisve page
$(this).append(jumpIcons.clone());
});
演示:
简化版
var socials = $("ul a");
socials.append(function (index, elem) {
return $(this).find("i").clone();
});
演示:您可以使用
clone()
,请参见下面的代码
var socials = $("ul a");
socials.each(function ( index,elem ){
var jumpIcons = $( this ).find("i").clone();//make clone of i
$(this).append(jumpIcons);// use $(this) to get current element
});
只需为每个
a
克隆i
和它的所有事件(如果需要)并将附加到a
。尝试-
var socials = $("li a");
socials.each(function ( index, elem ){
var jumpIcons = $( this ).find("i").clone(true, true); //remove true, true if you dont need the events
$(this).append(jumpIcons);
});
请解释一下,你到底需要什么?我还有一个问题:当我想悬停在i:first child上时,它会转到top:-42px,last-child会转到top:0px。我怎么做?
var socials = $("ul a");
socials.append(function (index, elem) {
return $(this).find("i").clone();
});
var socials = $("ul a");
socials.each(function ( index,elem ){
var jumpIcons = $( this ).find("i").clone();//make clone of i
$(this).append(jumpIcons);// use $(this) to get current element
});
var socials = $("li a");
socials.each(function ( index, elem ){
var jumpIcons = $( this ).find("i").clone(true, true); //remove true, true if you dont need the events
$(this).append(jumpIcons);
});