简体   繁体   English

使用JS / Jquery在现有HTML元素中添加图像

[英]Add an image in existing HTML element with JS/Jquery

On my webpage there are Gridster widgets.These widgets have images in them which can be deleted.Now I have a + button when user clicks on it a modal opens which shows list of images.Now I want users to select an image(click on it) and then press Add Image then that images should get added in the widget specified. 在我的网页上有Gridster小部件。这些小部件中都有可以删除的图像。现在我有一个+按钮,当用户点击它时会打开一个显示图像列表的模态。现在我希望用户选择一个图像(点击然后按Add Image然后在指定的小部件中Add Image

Also the images which are shown in modal are retrieved from server so I cannot manually place element like id to differentiate them.I think this in jquery will help in getting a specific image that is clicked.Along with that the image added should have same structure like that of existing image. 此外,其在模态显示的图像是从服务器中检索,所以我不能手动放置元素像id来区分他们。我想this在jQuery将在得到一个与该clicked.Along特定图像帮助添加图像应该具有相同的结构像现有的图像。

'<div class="imagewrap"><img src= image i click > <input type="button" class="removediv" value="X" /></div></div>';

I also want to update the textarea field with the src of the image I added just like it is with the other existing images. 我还想用我添加的图像的src更新textarea字段,就像它与其他现有图像一样。

HTML: HTML:

<div class="gridster">
    <ul>

    </ul>

</div>
<button class="js-seralize btn btn-success mr-2">Serialize</button>
<textarea id="log"></textarea>

<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Add Icons</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

            <img src="https://cdnd.icons8.com/wp-content/uploads/2015/07/Run-Command-100.png">
      <img src="https://png.icons8.com/metro/2x/chapel.png">
      <img src="https://png.icons8.com/metro/2x/boy.png">
      <img src="https://png.icons8.com/metro/2x/wacom-tablet.png">






      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Add Image</button>
      </div>
    </div>
  </div>
</div>

JS: JS:

var gridster;


gridster = $(".gridster ul").gridster({
  widget_base_dimensions: [100, 100],
  widget_margins: [5, 5],
  helper: 'clone',
   serialize_params: function($w, wgd) {return {images: $w.find('textarea').val().trim() , col: wgd.col, row: wgd.row, size_x: wgd.size_x, size_y: wgd.size_y}},
  resize: {
    enabled: true
  }
}).data('gridster');


 var json = [{
    "html": "https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", //3 Images
    "col": 1,
    "row": 1,
    "size_y": 2,
    "size_x": 2
}, {
    "html":"https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", // 2 Images
    "col": 4,
    "row": 1,
    "size_y": 2,
    "size_x": 2
},

{
    "html": "https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", // 1 Image
    "col": 6,
    "row": 1,
    "size_y": 2,
    "size_x": 2
},


{
    "html": "https://image.flaticon.com/icons/svg/67/67994.svg,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png",  // 2 Images
    "col": 1,
    "row": 3,
    "size_y": 1,
    "size_x": 1
}, {
    "html": "https://image.flaticon.com/icons/svg/67/67994.svg", //1 Image
    "col": 4,
    "row": 3,
    "size_y": 1,
    "size_x": 1
},

{
    "html": "https://image.flaticon.com/icons/svg/67/67994.svg,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", //2 Images
    "col": 6,
    "row": 3,
    "size_y": 1,
    "size_x": 1
}

];








for(var index=0;index<json.length;index++) {
    var images = json[index].html.split(',');
        var imageOutput = "";

        for(var j = 0; j < images.length; j++) {
        imageOutput += '<div class="imagewrap"><img src='+ images[j] +'> <input type="button" class="removediv" value="X" /></div></div>';
        }

gridster.add_widget('<li class="new" ><button class="addmorebrands" style="float: left;">+</button><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>'+json[index].html+'</textarea></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row);
}









$('.removediv').on('click', function () {
  $(this).closest('div.imagewrap').remove();
});


 $(document).on("click", ".delete-widget-button", function() {
        var gridster = $(".gridster ul").gridster().data('gridster');
        gridster.remove_widget($(this).parent());
    });


$('.js-seralize').on('click', function () {
    var s = gridster.serialize();
    $('.gridster ul li').each((idx, el)=>{ // grab the grid elements
       s[idx].html = $('textarea', el).html(); // add the html key/values

    json_variable=JSON.stringify(s)
   });



    $('#log').val(json_variable);
});

$(document).on("click", ".addmorebrands", function() {
        $('#exampleModalCenter').modal('show');

    });

Someone please help me with this as I am finding it really difficult to get it 有人请帮助我,因为我发现很难得到它

Fiddle Link 小提琴链接

The adding the image part is up and running now, at least in its raw, modified and added some code in this section: 添加图像部分现在已启动并运行,至少在其原始版本中已修改并添加了本节中的一些代码:

//EDITS
var parentLI;
$(document).on("click", ".addmorebrands", function() {
    parentLI = $(this).closest('li');
    $('#exampleModalCenter').modal('show');
    $('#exampleModalCenter img').click(function(){
        $(this).addClass('preselect');
        $(this).siblings().removeClass('preselect');
        selectedImageSRC = $(this).attr('src');
    });
});

$('#add-image').click(function(){
    parentLI.append('<div class="imagewrap"><img src="'+selectedImageSRC+'"> 
    <input type="button" class="removediv" value="X" /></div>');
    parentLI.children('textarea')
       .append(', '+selectedImageSRC);
    $('#exampleModalCenter').modal('hide');
});

and this too: 这也是:

.preselect{
  border: 2px solid white;
  background: green
}

.preselect:hover{
  border: 1px solid white;
  background: lightgreen
}

I'll leave you the part of resizing the images inside each cell, and also everything else :) https://jsfiddle.net/0ndht0zh/23/ 我会告诉你每个单元格内部图像的大小调整,以及其他所有内容:) https://jsfiddle.net/0ndht0zh/23/

UPDATE UPDATE

This code only applies to .removediv which exist at the time it runs: 此代码仅适用于.removediv存在的.removediv

$('.removediv').on('click', function () {
    $(this).closest('div.imagewrap').remove();
});

Which is why preexisting images do get deleted but not those you add later. 这就是为什么预先存在的图像会被删除但不是之后添加的图像。 I'm no expert so please do research for a more technical explanation, but basically: 我不是专家所以请研究更多技术解释,但基本上:

Following code does almost the same, except since it is attached to document (but applied to .removediv ) which actually existed by the time this code ran, the event will always find its way to .removediv . 下面的代码几乎完全相同,除非它附加到document (但应用于 .removediv ),这个代码运行时实际存在,事件总是会找到.removediv

$(document).on('click', '.removediv', function () {
    $(this).closest('div.imagewrap').remove();
});

updated fiddle: https://jsfiddle.net/0ndht0zh/27/ 更新小提琴: https//jsfiddle.net/0ndht0zh/27/

also remember to update the textarea content on deletion 还记得在删除时更新textarea内容

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

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