簡體   English   中英

編輯:如何動態創建div?

[英]edit: How can I dynamically create divs?

我正在嘗試創建一個條形圖。 我在處理一堆代碼時遇到了麻煩,但是最大的問題是我似乎無法創建一個循環,該循環將把我的sampleData數組中的數據並每次創建一個新的div並將其附加到下一個div等等。 現在,我已經簡單地創建了5個div,但是我不需要很多。

另外,我想將鼠標懸停在欄上並查看項目數。

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="testMyJson.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
    $(document).ready(function() {
    $.support.cors = true;
    $.ajax({
    url:'https://www.sciencebase.gov/catalog/items?q=Fish&max=20&format=json',
    type: "GET",
    dataType: "json",
    success: function( response ) {
    var sampleData = [25,7,19,22,150];

    //for (var i = 0; i < 5; i++) {
        $('#super-skill-1').animate( { height:sampleData[0] + 'px' } );
        $('#super-skill-2').animate( { height:sampleData[1] + 'px' } );
        $('#super-skill-3').animate( { height:sampleData[2] + 'px' } );
        $('#super-skill-4').animate( { height:sampleData[3] + 'px' } );
        $('#super-skill-5').animate( { height:sampleData[4] + 'px' } );
    //}


    },
    error: function(jqXHR, textStatus, errorThrown) {
            alert("Ajax Call Failed - textStatus =" +  textStatus + ", errorThrown = " + errorThrown);
}
});
});
</script>
<style>
.the-container { width:400px; height:250px; border-style: solid; border-width:3px; border-color:black }
.the-container ul { margin:0; padding:0; list-style:none; }
.the-container li { width:30px; height:250px; margin:0 5px; position:relative; float:left; }
.the-container li a { position:absolute; bottom:0; width:100%; height:0; background-color:#ccc; }
.the-container li a:hover { background-color:green; }
</style>
</head>
<body>
<div class="the-container">
<ul>
<li><a id="super-skill-1" href="#" class="tooltip" title=sampleData[0]></a></li>
<li><a id="super-skill-2" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-3" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-4" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-5" href="#" class="tooltip" title="TESTING!!!!"></a></li>
</ul>
</div>
<form>
<input type="button" id="showdata"value="Show Data" >


</form>
</body>
</html>

謝謝

數組迭代可以通過$ .each函數執行。 要從數組創建div集,可以使用以下方法:

myArray -陣列創建,申報單#divContainer -元素的ID來放置新的div在

1)使用append 如果您需要設置應用於新元素的屬性或樣式,那就很好

$.each(myArray, function(elem) {
      $("#divContainer").append($("<div></div>").css("background", "red").html(elem));
});

2)使用字符串連接。 比添加更快。

var result = "";
$.each(myArray, function(elem) {
        result += "<div>" + elem + "</div>";
    });
$("#divContainer").append($(result));

3)使用jquery.tmpl -jQuery的模板插件。 快速簡單的方法,但需要其他插件

$.tmpl("{{each}}<div>{{html $value}}",
       myArray)
 .appendTo("#divContainer" );

我刪除了AJAX調用以對其進行測試。 這似乎適用於循環:

for (var i = 0; i < 5; i++) {      
    $('#super-skill-' + i).animate( { height:sampleData[i] + 'px' } );
}

我建議將sampleData中的索引與id中的索引匹配。

<li><a id="super-skill-0" href="#" class="tooltip" title=sampleData[0]></a></li>
<li><a id="super-skill-1" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-2" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-3" href="#" class="tooltip" title="TESTING!!!!"></a></li>
<li><a id="super-skill-4" href="#" class="tooltip" title="TESTING!!!!"></a></li>

如果您的樣本數據來自響應(作為數組),則可以

for (var i in response) {
    var newDiv = $('<div id="super-skill-'+i+'"/>)
    $('#parentDiv').append(newDiv);
    newDiv.animate( { height:sampleData[i] + 'px' } );
}

實際並未回答您的問題,但有一點好處。

您不需要將px添加到動畫或css,寬度,高度等中。如果您將單位省略,jQuery將假定px。

你的

$('#super-skill-' + i).animate( { height:sampleData[i] + 'px' } );

$('#foo').animate({top: 100, left: 80 }, 1200);

http://jsfiddle.net/UqPmB/

您可以使用$ .each函數循環遍歷並動態添加li / anchor標簽

var sampleData = [25, 7, 19, 22, 150,60,99,56];

$('input[type=button]').click(function() {
    $.each(sampleData, function(i, v) { // loop through each item in array 
                        //i=indexInArray,v=valueOfElement
        var $lis = $('<li><a></a></li>'); // create new li's with children anchors
        $lis.find('a') // find anchor
            .attr('id', 'super-skill-' + (i + 1)) // add id
            .attr('href', '#') // add href
            .attr('title', v) // add title
            .addClass('tooltip'); // add class tooltip
        $('div.the-container ul').append($lis); // add to ul
        $('#super-skill-'+ (i + 1)).animate( { height:v  } ,1000);  // animate
    });
});​

的jsfiddle

不同的方法

您是否考慮過使用專門設計用於繪制圖表的庫,例如gRaphaël

使用gRaphaël,您只需編寫:

r.barchart(10, 10, 400, 250, [sampleData]);

而且您不必理會sampleData中有多少元素,如何迭代它們,如何縮放它們,考慮其可變數量的條形寬度應該是多少,最大值是多少,以便您知道如何縮放垂直等

這是您的程序看起來像包括懸停時出現的值的樣子:

條形圖示例

var sampleData = [25,7,19,22,150,200,25,77,30,105,5];

var r = Raphael("chart");

// hover handlers:                      
function fin() {
    this.flag = r.popup(this.bar.x, this.bar.y,
                  this.bar.value || "0").insertBefore(this);
}
function fout() {
    this.flag.animate({
        opacity: 0
    }, 600, function() {
        this.remove();
    });
}

r.barchart(10, 10, 400, 250, [sampleData]).hover(fin, fout);

就是這樣。

查看演示

(懸停事件處理程序是gRaphaël網站上示例的處理程序的修改版。)

它適用於Firefox 3.0 +,Safari 3.0 +,Opera 9.5+和Internet Explorer 6.0+。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM