2011-07-19 39 views
1

当我点击一个链接时,我尝试添加一个字段集。如何使用.append()和appendTo()添加我们想要的元素?

我会认为这个新元素在我的范围之前,因为在这个时候元素被添加了。

<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> 

所以,你明白:良好的结果应该是这个

<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> 

要添加新的字段集,我这样做:

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

是否有可能加入其中我们想要 ?

+0

内嵌的JavaScript('的onclick = “... ”')和'HREF =“ JavaScript的:” ......'是完全DIS推荐的,尤其是* *当你已经拥有的东西像jQuery的地方。 – Tomalak

+0

感谢提示 – bahamut100

回答

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

这应该做的伎俩。它使用after#fieldsetOptions的子legend之后插入新元素。

0

prepend也是一个函数,你有前后方法。 如果你想要它之间的元素,prepend和append不会工作,之前和之后可以做到这一点。在准备功能

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

(并给予锚一类特殊效果会更好): 我不会用的onclick,但用这个。

0

这将在跨度之前插入新元素,但如果您打算在将来拥有更多跨度,则应至少为跨度赋予一个类,以便您只能定位所需的跨度。

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

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

相关问题