jQuery before()和insertBefore()方法都执行相同的任务,在匹配的元素之前添加文本或html内容。 主要区别在于语法。
例如,
<div class="prettyBox">I'm a ipman</div><div class="prettyBox">I'm a ipman 2</div> 1. $('selector')。before('new content'); $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>"); 2. $('new content')。insertBefore('selector'); $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox'); 结果上面的两个方法都执行相同的任务,但是使用不同的语法, before()或insertBefore()之后的新内容将变为
<div class='newPrettybox'>Iron man</div><div class="prettyBox"> I'm a ipman</div><div class='newPrettybox'>Iron man</div><div class="prettyBox"> I'm a ipman 2</div> 自己尝试 <html><head><script type="text/javascript" src="jquery-1.3.2.min.js"></script><style type="text/css">.prettyBox{padding:8px;background: grey;margin-bottom:8px;width:300px;height:100px;}.newPrettybox{padding:8px;background: red;margin-bottom:8px;width:200px;height:50px;}</style></head><body> <h1>jQuery before() and insertBefore() example</h1> <div class="prettyBox">Ip man</div> <div class="prettyBox">Ip man 2</div> <p> <button id="before">before()</button> <button id="insertBefore">insertBefore()</button> <button id="reset">reset</button> </p> <script type="text/javascript"> $("#before").click(function () { $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>"); });$("#insertBefore").click(function () { $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox'); });$("#reset").click(function () { location.reload(); });</script></body></html> 试试演示 标签: jquery jquery操作翻译自: https://mkyong.com/jquery/jquery-before-and-insertbefore-example/
85775094