开发者

How to add elements where we want with .append() and appendTo()?

I try to add a fieldset when I'm clicking on a link.

I would that this new element is before my span, because at this moment, elements are add after.

<fieldset id="fieldsetOptions">
 <legend>Options</legend>
 <span>Add an option
   <a onclick="addOption()" href="javascript:return false;">
    <img src="./images/开发者_如何学运维icons/add.png">
   </a>
 </span>
 <fieldset><!--this is the new fieldset, but not at the good place--></fieldset>
</fieldset>

So, you understand : The good result should be this

<fieldset id="fieldsetOptions">
 <legend>Options</legend>
 <fieldset><!--this is the new fieldset, at the good place--></fieldset>
 <span>Add an option
   <a onclick="addOption()" href="javascript:return false;">
    <img src="./images/icons/add.png">
   </a>
 </span>     
</fieldset>

To add the new fieldset, I'm doing this :

<script type="text/javascript">
    function addOption(){
     $("#fieldsetOptions").append("<fieldset></fieldset>");
    }
</script>

Is it possible to add where we want ?


$("#fieldsetOptions legend").after("<fieldset></fieldset>");

That should do the trick. It uses after to insert the new element after the legend child of #fieldsetOptions.


This will insert your new element before the span, but you should give the span at least a class if you plan to have more spans in the future, so you can target only the span you want.

<script type="text/javascript">
    function addOption(){
     $("#fieldsetOptions > span").before("<fieldset></fieldset>");
    }
</script>

http://api.jquery.com/before/


prepend is a function too, and you have before and after-methods. If you want it between elements, both prepend and append won't work, after and before could do it. I wouldn't use a onclick, but use this:

$("#fieldsetOptions > span > a").click(function() {
    $(this).closest('span').before("<fieldset></fieldset>");
});

in the ready-function (and giving the anchors a specific class would be better).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜