简体   繁体   中英

img and p within div using D3JS

I want to have a div's containing images and image-titles. I manage to get the images with the following code, but can't combine images and text within div's.

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

You can see a working example at 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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