编辑:如何动态创建div?

时间:2012-10-04 20:30:58

标签: javascript jquery html css

我正在尝试创建一个条形图。我遇到了很多代码的问题,但最大的问题是我似乎无法创建一个循环来获取我的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>

由于

6 个答案:

答案 0 :(得分:1)

可以通过$.each函数执行迭代数组。 要从数组中创建div set,可以使用以下方法:

myArray - 为其创建div的数组,  #divContainer - 在

中放置新div的元素ID

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使用jquery.tmpl - 模板插件。快速简单的方法,但需要额外的插件

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

答案 1 :(得分:0)

我删除了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>

答案 2 :(得分:0)

如果您的样本数据来自响应(作为数组),那么您可以

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

答案 3 :(得分:0)

实际上没有回答你的问题,只是一点点奖励。

您不需要将px添加到动画或css,宽度,高度等。如果您将设备退出,jQuery会假设为px。

此致

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

实施例

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

http://jsfiddle.net/UqPmB/

答案 4 :(得分:0)

您可以使用$.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

答案 5 :(得分:0)

不同的方法

您是否考虑过使用专门设计的图书馆来绘制图表, 比如gRaphaël

使用gRaphaël你只需写:

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

并且你不关心你在sampleData中有多少元素,如何迭代它们,如何缩放它们,考虑到它们的变量数,条形的宽度应该是多少,最大值是什么,所以你知道如何垂直缩放等等。

这是你的程序的样子,包括悬停时出现的值:

bar chart example

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);

就是这样。

SEE DEMO

(悬停事件处理程序是gRaphaël网站上示例中处理程序的修改版本。)

适用于Firefox 3.0 +,Safari 3.0 +,Opera 9.5+和Internet Explorer 6.0 +。

相关问题