2012-06-25 90 views
5

我需要帮助在页面主体中的特定位置添加元素。jQuery:在第n个元素后添加元素

这是我的页面代码。

<div id="div1> 
    <label id="label1"></label> 
    <input type="text1"></input> 
    <!-- Insert button here --> 
    <span id="span1"></span> 
</div> 

我想添加一个按钮,我在上面使用jQuery发表评论的位置。如果页面语法是固定的,有没有办法将一个元素添加为父div的第三个子元素?我不想放置占位符并进行字符串替换。

谢谢。

+1

'type =“text1”'不应该是'type =“text”name =“text1”'? –

+0

我知道你说*页面语法是固定的*,但我坚信防守编程。所以,你应该问自己,如果一个新的元素被添加到'#div1'中,它会对事物产生什么影响?那么,如果在输入之前添加它,则必须调整代码以将按钮作为第四个*孩子插入。假设按钮总是会在'input'元素后面右移是否安全?如果是这样,我会避免在某个索引后添加。 – lbstr

回答

1
button.insertAfter($('#div1').children().eq(1)); 

这将插入button#后的第二个孩子DIV1

1
function insertAfterNthChild($parent, index, content){ 
    $(content).insertAfter($parent.children().eq(index)); 
} 

// Usage: 
insertAfterNthChild($('#div1'), 1, '<button>Click me!</button'); 
0

的jQuery已经只是为此做了nth-child()选择。

$("input:nth-child(1)").after("<your html here>"); 
+1

':第n-child'是CSS3的规范,是1索引不是0 –

0

您可以通过多种方式实现这一点..下面是一个,

//     v--- Change n to insert at different position 
$('#div1 :nth-child(2)').after('<button>Test</button>'); 

DEMO:http://jsfiddle.net/m5Gyz/

相关问题