2012-06-25 105 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/

相關問題