.append(), prepend(), .after() and .before()
我非常精通编码,但偶尔我会遇到似乎基本相同的代码。 我的主要问题是,为什么你会使用
我一直在寻找,似乎无法找到两者之间的差异的明确定义,何时使用它们以及何时不使用它们。
一个优于另一个的好处是什么?为什么我会使用一个而不是另一个? 有人可以向我解释一下吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var txt = $('#' + id + ' span:first').html(); $('#' + id + ' a.append').live('click', function (e) { e.preventDefault(); $('#' + id + ' .innerDiv').append(txt); }); $('#' + id + ' a.prepend').live('click', function (e) { e.preventDefault(); $('#' + id + ' .innerDiv').prepend(txt); }); $('#' + id + ' a.after').live('click', function (e) { e.preventDefault(); $('#' + id + ' .innerDiv').after(txt); }); $('#' + id + ' a.before').live('click', function (e) { e.preventDefault(); $('#' + id + ' .innerDiv').before(txt); }); |
看到:
假设:
1 2 | //<---you want div c to append in this b |
当
1 | $('.a').append($('.c')); |
执行后:
1 2 3 | //<---you want div c to append in this b c |
在执行中摆弄.append()。
当
1 | $('.a').prepend($('.c')); |
执行后:
1 2 3 | //<---you want div c to append in this c b |
在执行中使用.prepend()。
使用后:
1 | $('.a').after($('.c')); |
执行后:
1 2 3 | b c //<----this will be placed here |
在执行中摆弄.after()。
之前使用:
1 | $('.a').before($('.c')); |
执行后:
1 2 3 | c //<----this will be placed here b |
在执行中摆弄.before()。
下面显示的图像清晰地理解并显示
您可以从图像中看到
并且
这是一个更好理解的DEMO。
编辑:这些功能的翻转版本:
使用此代码:
1 2 3 4 5 6 7 8 9 10 11 | var $target = $('.target'); $target.append('1. append'); $target.prepend('2. prepend'); $target.before('3. before'); $target.after('4. after'); $('or appendTo').appendTo($target); $('or prependTo').prependTo($target); $('or insertBefore').insertBefore($target); $('or insertAfter').insertAfter($target); |
在这个目标上:
1 | This is the target div to which new elements are associated using jQuery |
因此,虽然这些函数会翻转参数顺序,但每个函数都会创建相同的元素嵌套:
1 2 | var $div = $('').append($('<img>')); var $img = $('<img>').appendTo($('')) |
......但它们会返回不同的元素。这对方法链很重要。
最好的方法是记录文档。
-
。
append() :将参数指定的内容插入到匹配元素集中每个元素的末尾。 -
。
after() :在匹配元素集中的每个元素之后插入由参数指定的内容。
-
prepend() :将参数指定的内容插入到匹配元素集中每个元素的开头。 -
。
before() :在匹配元素集中的每个元素之前插入由参数指定的内容。
因此,append和prepend指的是对象的子对象,而after和before指的是对象的兄弟对象。
反之亦然
小提琴
1 2 3 4 5 6 7 | // <-- $(".root").before(""); // <-- $(".root").prepend(""); // <-- $(".root").append(""); // <-- $(".root").after(""); |
每个人都没有额外的优势。这完全取决于你的情况。下面的代码显示了它们之间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | Before inserts your html here Prepend inserts your html here <span> Home </span> <span> About Us </span> <span> Contact Us </span> Append inserts your html here After inserts your html here |
试着回答你的主要问题:
为什么你会使用.append()而不是.after()或反之?
当您使用jquery操作DOM时,您使用的方法取决于您想要的结果,并且经常使用的是替换内容。
在替换内容时,您需要
想象一下DOM(HTML页面)作为树权。 HTML元素是此树的节点。
1 2 3 4 5 6 | Example:$("#mydiv").append("<p> Hello there </p>") creates a child node <p> to |