2010-05-10 42 views
1

我正在開發一個使用javascript的應用程序。我需要的是使用id的div(1,2,3 ...),並且能夠在jquery之間插入div(例如2和3),然後讓它成爲新的三個,並且三個成爲四,四變爲五等。我有div插入工作,我只需要知道如何重新排列div。有任何想法嗎?當使用Javascript在中間添加一個div時,對數字順序的div ID進行重新編號

+3

讓我成爲第一個要注意的是純數字「ID」值無效。 – Pointy 2010-05-10 22:31:41

+0

...除非(也許)您使用HTML5 :-)(謝謝@edwin!) – Pointy 2010-05-10 22:44:45

回答

3

後您插入新的div,你可以這樣做:

var i = 1; 
$('div').each(function() { 
    $(this).attr('id', i++); 
}); 

由你自己選擇替換$( '格')。

還請記住,根據您使用的HTML版本,id不能以數字開頭。

+0

HTML5是否放寬了「id」值規則? – Pointy 2010-05-10 22:33:28

+0

是的。或者至少它是HTML5的建議:id可以包含任何內容,所以即使是id =「+ *(*%*^{|'」也是有效的(我仍然不知道該怎麼想:-)) – edwin 2010-05-10 22:41:32

+0

你也可以使用each()給出的索引,而不是維護一個計數器。 – tster 2010-05-10 22:44:30

0

我很確定你從DOM選擇器返回DOM順序,所以你不能找到父元素,選擇子元素<div>,然後.each()通過列表?

1

你不能用一個數值開始ID,但不管你會做這樣的事情

// set a data value in the div you have just inserted into the dom and set a variable theID to the current ID you have just inserted. 

$(this).data('inserted', true); 
var theID = $(this).attr('id'); // this will be 3. 


// now to update the other divs. 
$('div').each(function() { 
    if($(this).attr('id') >= theID && !$(this).data('inserted')){ 
     $(this).attr('id', $(this).attr('id') + 1); 
    } 
}); 

// now set the data inserted to false for future updates 
$('div#3').data('inserted', false); 
1
$(function() { 

    reorder(); 

    $('#click').click(function() { 

    $('<h2>hello world blah!</h2>').insertAfter('.content h2:eq(1)'); 
    reorder(); 
    }); 

}); 

function reorder() { 
$('.content h2').each(function(i) { 
    $(this).attr('id', 'order_'+(i+1)); 
// alert(parseInt(this.id.split('_')[1])); // this is the id # 
}); 
}; 
相關問題