2013-07-10 37 views
1

我正在用raphaeljs創建一堆圖表,並且我希望在頁面加載後將它們添加到特定div的內容中。使用jQuery將raphael生成的圖表添加到文檔中

這裏是我的html:

<div class="chartdiv"> 
    <span class="A">35</span> 
    <div class="charthere"></div> 
</div> 

<div class="chartdiv"> 
    <span class="A">25</span> 
    <div class="charthere"></div> 
</div> 

<div class="chartdiv"> 
    <span class="A">15</span> 
    <div class="charthere"></div> 
</div> 

下面的jQuery代碼應該通過與類chartdiv,併爲每個

  • 所有div環與A級的跨度中獲得的價值,
  • 將它傳遞給drawChart功能
  • 把SVG在div與類charthere

這裏我的JS腳本的相關部分:

$(document).ready(function(){ 

    $('div.chartdiv').each(function(){ 
     // get the A value 
     var A = parseInt($(this).add('span.A').text()); 

     // substitute the html with the corresponding chart 
     drawChart($(this).add('div.charthere'), A); 
    }); 

    function drawChart(element, A) { 
     var paper = new Raphael(element, 200, 200); 
     var examplePathString = "M20,100 L" + A + ",100"; 
     var thePath = paper.path(examplePathString); 
     thePath.attr({stroke: red,'stroke-width': 5px}); 
    } 
}); 

反而會發生什麼情況是,所有的SVG元素的div後創建。

回答

1

有兩個問題:

1--使用jQuery's .add()增加什麼除了無論是在它已經選擇匹配的選擇。

因此,每個.add('div.charthere')增加每div.charthere到選擇(沒有縮小到兒童div.chartdiv的),旁邊div.chartdiv

它看起來像你試圖做的是從div.chartdiv下降到div.charthere在那div。爲此,您需要.find('div.charthere')(或者,如果它是總是將只是一步下降,.children('div.charthere'))。

2--您正在將一個代表jQuery選擇div的jQuery對象傳遞給Raphael。 Raphael期望一個DOM元素(div本身)或一個ID字符串。 Raphael不是jQuery插件,所以它不知道如何處理jQuery對象。

jQuery對象就像一個修改過的數組,充當實際DOM元素的包裝,因此您可以使用$someObj[0](只要它是您感興趣的第一個項目)就可以獲得dom元素本身。

所以,.find('div.charthere')[0]應該做的工作。


你需要確保你傳遞給Raphael();什麼是一個DOM元素或字符串。將console.log(element);添加到您的函數的開頭,並在像Firebug這樣的調試器中查看控制檯,並且您可能會每次看到比您想要的更多的元素。

(也通常不需要的newnew Raphael() - var paper = Raphael() is what is suggested in the official docs - 但我不認爲這是問題的原因)

+0

感謝您指出了這一點。通過查看console.log,我能夠通過遵循您的建議並使用.children('span.A').text()而不是.add('span.A ')。文本()。實例化Raphael對象時,我也刪除了'new'。 –

+0

仍然帶drawChart($(this).children('div.charthere'),A);它看起來像看着控制檯,傳遞的元素是div的(空)內容而不是div本身。 –

+1

這讓我意識到還有第二個問題 - 請參閱上面的編輯 – user568458

相關問題