简体   繁体   English

使用D3JS在div中的img和p

[英]img and p within div using D3JS

I want to have a div's containing images and image-titles. 我想要一个包含图像和图像标题的div。 I manage to get the images with the following code, but can't combine images and text within div's. 我设法通过以下代码获取图像,但是无法在div内合并图像和文本。

function update(sel) {
        console.log('update')
        console.log(sel)
        update_images(d3.select("#fotoos"), sel);
}

function update_images(ul, data) {
  var image = ul.selectAll("img").data(data);
  image.exit().remove();
  image.enter().append("img");
  image.attr("class", "foto");
  image.attr("src", function(d) {
      var u = '{{ =URL('download') }}'
      return u.concat("/", d.file) })
}

How can I get the following? 我如何获得以下内容?

<div>
   <p ...
   <img ...
</div>

Thank you, Richard 谢谢理查德

Note: The {{ }} code do come from Web2Py 注意:{{}}代码确实来自Web2Py

You can see a working example at http://jsfiddle.net/zceg2/1/ . 您可以在http://jsfiddle.net/zceg2/1/上看到一个工作示例。

You need to create the container element first (the div in this case) and then use that selection to append your text and images. 您需要先创建容器元素(在这种情况下为div ),然后使用该选择内容来添加文本和图像。

var data = [{id: 1, text: 'sample text 1', imgsrc: 'http://placehold.it/100x100'},
            {id: 2, text: 'sample text 2', imgsrc: 'http://placehold.it/100x100'},
            {id: 3, text: 'sample text 3', imgsrc: 'http://placehold.it/100x100'},
            {id: 4, text: 'sample text 4', imgsrc: 'http://placehold.it/100x100'}];

var gallery = d3.select('body').append('div');

var container = gallery.selectAll('.container')
    .data(data, function(d) { return d.id; });

container.enter().append('div')
    .attr('class', 'container')

container.exit().remove();


container.selectAll('.text')
    .data(function(d) { return [d]; })
    .enter().append('p')
    .attr('class', 'text')
    .text(function(d) { return d.text; });

container.selectAll('.picture')
    .data(function(d) { return [d]; })
    .enter().append('img')
    .attr('class', 'picture')
    .attr('src', function(d) { return d.imgsrc; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM