简体   繁体   English

编辑:如何动态创建div?

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

I'm trying to create a bar graph. 我正在尝试创建一个条形图。 I'm having trouble with a bunch of the code, but the biggest problem is that I can't seem to create a loop that will take the data in my sampleData array and create a new div each time and append it to the next div and so on. 我在处理一堆代码时遇到了麻烦,但是最大的问题是我似乎无法创建一个循环,该循环将把我的sampleData数组中的数据并每次创建一个新的div并将其附加到下一个div等等。 For now I've simple created 5 divs, but I don't many I will need. 现在,我已经简单地创建了5个div,但是我不需要很多。

Also, I'd like to hover over the bar and see the number of items. 另外,我想将鼠标悬停在栏上并查看项目数。

<!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>

Thanks 谢谢

Iterating through array can be performed by $.each function. 数组迭代可以通过$ .each函数执行。 To create div set from array following methods can be used: 要从数组创建div集,可以使用以下方法:

myArray - array to create divs for, #divContainer - id of element to place new div's in myArray -阵列创建,申报单#divContainer -元素的ID来放置新的div在

1) Using append . 1)使用append Good if you need to set attributes or styles applied to new elements 如果您需要设置应用于新元素的属性或样式,那就很好

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

2) Using string concatenation. 2)使用字符串连接。 Faster than append. 比添加更快。

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

3) Using jquery.tmpl - template plugin for jQuery. 3)使用jquery.tmpl -jQuery的模板插件。 Fast and simple way but requires additional plugin 快速简单的方法,但需要其他插件

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

I removed the AJAX call to test it. 我删除了AJAX调用以对其进行测试。 And this seems to work for the loop: 这似乎适用于循环:

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

I would suggest having the indexes in sampleData match with those in the ids. 我建议将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>

If your sample data is coming from the response, (as an array) then you could do 如果您的样本数据来自响应(作为数组),则可以

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

Not actually answering your question, but a little bonus. 实际并未回答您的问题,但有一点好处。

You don't need to add px to animate or css, width, height etc. jQuery assumes px if you leave the unit out. 您不需要将px添加到动画或css,宽度,高度等中。如果您将单位省略,jQuery将假定px。

Yours 你的

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

Example

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

http://jsfiddle.net/UqPmB/ http://jsfiddle.net/UqPmB/

You can loop through and add li/anchor tags dynamically using $.each function 您可以使用$ .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 的jsfiddle

Different approach 不同的方法

Have you considered using a library that was designed specifically to draw charts, like gRaphaël ? 您是否考虑过使用专门设计用于绘制图表的库,例如gRaphaël

Using gRaphaël you just write: 使用gRaphaël,您只需编写:

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

and you don't care how many elements you have in sampleData, how to iterate them, how to scale them, what should be a good width of the bars considering their variable number, what would be the maximum value so you know how to scale it vertically, etc. 而且您不必理会sampleData中有多少元素,如何迭代它们,如何缩放它们,考虑其可变数量的条形宽度应该是多少,最大值是多少,以便您知道如何缩放垂直等

This is how your program would look like including the values that appear on hover: 这是您的程序看起来像包括悬停时出现的值的样子:

条形图示例

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

and that's it. 就是这样。

SEE DEMO 查看演示

(The hover event handlers are a modified version of the handlers from the examples on gRaphaël website.) (悬停事件处理程序是gRaphaël网站上示例的处理程序的修改版。)

It works in Firefox 3.0+, Safari 3.0+, Opera 9.5+ and Internet Explorer 6.0+. 它适用于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