2012-02-08 89 views
0

標記:插入父元素ID爲動態元素

<iframe id="portal"> 
    <div id="callout-1" class="callout"> 
    </div> 

    <div id="callout-2" class="callout"> 
    </div> 
</iframe> 

$(document).ready(function(){ 
    $('#page-portal').load(function(){ 
     $('#portal').contents().find('.callout') 
     .append('<div class="edit-image" id="edit-image-1">Edit This Area</div>'); 
    }); 
}); 

此代碼動態地插入一個div class="edit-image"到每個div class="callout"

我想要做的是從div class="callout" retreive的ID(數字部分)和動態插入它的編號爲div class="edit-image"

我遇到了麻煩,有誰能幫忙嗎?

+0

當你們要開始使用數據屬性的? – meo 2012-02-08 12:58:05

回答

2

您可以使用Javascript的.split()方法。它應該是這個樣子

$('#portal').find('.callout').each(function(k,v) { 
    id = $(this).attr("id"); 
    //take out the id of element 

    temp = id.split("-"); 
    //split the string based on "-" 

    idnum = temp[1]; 
    //take the second part of split i.e the integer part 

    $(this).append('<div class="edit-image" id="edit-image-'+idnum+'">Edit This Area</div>'); 
    //then finally use it 
}); 

這裏工作demo

1

你可以問一個元素的ID與

var id  = $("selektor").attr("id"), 
    number = parseInt(id.split('-')[1]); 

http://api.jquery.com/attr/

你的情況,你必須遍歷所有.callout的文檔中,然後解析id作爲上面再使用正確的ID插入新元素。