简体   繁体   English

如何在第一个img标签之前和2 img标签之后添加html代码

[英]how can I add html code before the 1st img tag and after 2 img tag

I am using an html which looks like the code below. 我使用的html看起来像下面的代码。 I am using a javascript code to replace or add code before the 1st img tag and add code after the 2nd img tag. 我使用javascript代码在第一个img标记之前替换或添加代码,并在第二个img标记之后添加代码。 How can I do it? 我该怎么做?

<body>
    <p>test</p>
    <img src="test.png" />
    <img src="test2.png" />
    <p>test</p>
    <img src="test3.png" />
    <img src="test4.png" />
    <p>test></p>
</body>

js: JS:

    var Children  = document.getElementsByClassName('img-responsive');
    for (i = 0; i <Children.length; i++) {
        alert(Children[i].innerHTML);
        Children[i].innerHTML = Children[i].id;
        if(i==1 && i==3) {
            string = string.split('<img').join(' <div class="row"> <div class="col-md-2"><img class="img-responsive" ');    
        }

        if(i==0 && i==2) {
            string=string.split('<img').join(' <div class="row"> <div class="col-md-2"><img class="img-responsive" ');
        }
    }

Desired output : 期望的输出:

<body>
    <p>test</p>
<div class=“row”>
<div class=“col-md-6”>
    <img class=“img-responsive" src="test.png" />
    <img src="test2.png" />
</div>
</div>
    <p>test</p>
    <div class=“row”>
 <div class=“col-md-6”>
    <img class=“img-responsive" src="test3.png" />
    <img class=“img-responsive" src="test4.png" />
</div>
</div>
    <p>test></p>
</body>

You can loop through all img tags in body and use wrapAll() method like following. 您可以循环遍历body中的所有img标记,并使用wrapAll()方法。

 var imgs = $('body > img'); for (var i = 0; i < imgs.length; i += 2) { var add = imgs.eq(i).add(imgs.eq(i + 1)); add.wrapAll('<div class="row"><div class="col-md-6"></div></div>'); } 
 .col-md-6 { background-color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <p>test</p> <img src="test.png" /> <img src="test2.png" /> <p>test</p> <img src="test3.png" /> <img src="test4.png" /> <p>test</p> </body> 

In a comment, you stated that you want to insert Before 1st and 3rd image [Odd indexed images] element and After 2nd and 4th image [Even indexed images]. 在评论,你说,你要插入Before第一和第三图像[奇数索引图像]元素,并After第二和第四图像[即使索引图像。 Here is a possible solution 这是一个可能的解决方案

 var images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { var _image = images[i]; if (i % 2 === 0) images[i].outerHTML = '<div class="row"><div class="col-md-6">' + images[i].outerHTML; else images[i].outerHTML += '</div></div>'; } 
 <body> <p>test</p> <img src="https://images.pexels.com/photos/285173/pexels-photo-285173.jpeg?h=350&auto=compress&cs=tinysrgb" alt="image 1" /> <img src="https://images.pexels.com/photos/287229/pexels-photo-287229.jpeg?h=350&auto=compress&cs=tinysrgb" alt="image 2" /> <p>test</p> <img src="https://images.pexels.com/photos/296878/pexels-photo-296878.jpeg?h=350&auto=compress&cs=tinysrgb" alt="image 3" /> <img src="https://images.pexels.com/photos/297755/pexels-photo-297755.jpeg?h=350&auto=compress&cs=tinysrgb" alt="image 4" /> <p>test</p> </body> 

As I see from your question, you are trying to do it with pure JS (good idea). 正如我从你的问题中看到的那样,你正试图用纯JS(好主意)来做。 I would suggest doing something like this: 我建议做这样的事情:

const imgs = document.querySelectorAll('img')

for (let i = 0; i < imgs.length; i = i + 2) {
  imgs[i].insertAdjacentHTML('beforebegin', `
    <div class="row">
      <div class="col-md-6"></div>
    </div>
  `)

  const container = imgs[i].previousElementSibling.querySelector('.col-md-6')
  container.appendChild(imgs[i])
  container.appendChild(imgs[i + 1])
}

Here's a JQuery Solution 这是一个JQuery解决方案

before = '<div class=“row”><div class=“col-md-6”>'
$imgOne = $('<div>').append($('body > img').eq(0).clone().addClass("img-responsive")).html();
$imgTwo = $('<div>').append($('body > img').eq(1).clone().addClass("img-responsive")).html();
after = '</div></div>'
$('body > img').eq(1).remove()
$('body > img').eq(0).replaceWith(before + $imgOne + $imgTwo + after)

this will produce the desired output for the 1st and 2nds img .eq(0) & .eq(1) that are direct children of body so after executing the function once the 3rd and 4th img will become the 1st and 2nd so simply running the function again will do the trick for you specific example. 这将产生第一个和第二个img .eq(0) & .eq(1)的所需输出,它们是身体的直接子项,因此在执行该函数后,一旦第3和第4个img将成为第1个和第2个,那么只需运行函数再次为你做特定的例子。

so be mindful of your selector and how your changes affect the index if img elements. 因此,请注意您的选择器以及您的更改如果影响img元素的索引。

in this case we are wraping the first 2 imgs in a div and this will shift the 3rd and 4th up 在这种情况下,我们将div中的前2个imgs包装起来,这将使第3个和第4个向上移动

I am using a javascript code to: 我使用的是一个javascript代码:

  • replace or add code before the 1st img tag and 在第一个img标签之前替换或添加代码
  • add code after the 2nd img tag. 在第二个img标签后添加代码。

Accomplished objective using: 完成目标使用:

Details are commented in Snippet. 详细信息在Snippet中进行了注释。

SNIPPET SNIPPET

 // Reference and collect all <img> in a NodeList var imgs = document.querySelectorAll('img'); /* This utilizes the .map() Array and .call() methods... || ...It also converts the NodeList into a true array. */ var imgArray = Array.prototype.map.call(imgs, function(obj, idx) { // Assign each <img> the .img-responsive class obj.className = "img-responsive"; // If the current index of <img> is an odd number... if (idx % 2 === 1) { /* .insertAdjacentHTML() is a method much like... || .innerHTML but better. */ obj.insertAdjacentHTML('afterend', '<div class="row"><div class="col-md-6"></div></div>'); // Reference the second image's sibling (.row) var row = obj.nextElementSibling; // Reference .row's child element. var bs = row.firstChild; // Assign a var to the first image of the pair. var imgA = imgs[idx - 1]; // Assign a var to the last image of the pair. var imgB = imgs[idx]; // Append images to .col-md-6 bs.appendChild(imgA); bs.appendChild(imgB); } return imgArray; }); 
 html, body { font: 400 16px/1.428 Verdana; } .row { background: rgba(0, 0, 0, .3); } .col-md-6 { border: 2px solid brown; } img { outline: 1px solid #eee; } p { font-size: 3.5rem; } 
 <p>test</p> <img src='http://placehold.it/150x150/e0f/eee?text=1'> <img src='http://placehold.it/150x150/e0f/eee?text=2'> <p>test</p> <img src='http://placehold.it/150x150/000/eee?text=3'> <img src='http://placehold.it/150x150/000/eee?text=4'> <p>test</p> <p>test</p> <img src='http://placehold.it/150x150/00f/eee?text=5'> <img src='http://placehold.it/150x150/00f/eee?text=6'> <p>test</p> <img src='http://placehold.it/150x150/f00/eee?text=7'> <img src='http://placehold.it/150x150/f00/eee?text=8'> <p>test</p> <p>test</p> <img src='http://placehold.it/150x150/080/eee?text=9'> <img src='http://placehold.it/150x150/080/eee?text=10'> <p>test</p> <img src='http://placehold.it/150x150/fc0/111?text=11'> <img src='http://placehold.it/150x150/fc0/111?text=12'> <p>test</p> 

In HTML 在HTML中

<body>
<p>test</p>
<img id="img1" src="test.png" style="">
<img id="img2" src="test2.png">
<p>test></p>
</body>

In JQuery 在JQuery中

$('#img1').before('content here');
$('#img2').after('content here');

If you have more than two images and you want to do specifically after the second element 如果您有两个以上的图像,并且您希望在第二个元素之后专门执行

$('img').first().before('Your html content here');
$('img:eq(1)').after('Your html content here'); 

If you prefer a pure JavaScript answer (whether for learning, a drip of performance or some other reason), then have a look at Node.appendChild() and Node.insertBefore() (MDN Links). 如果您更喜欢纯JavaScript答案(无论是学习,性能滴落还是其他原因),那么请查看Node.appendChild()Node.insertBefore() (MDN Links)。

See also these related SO questions: 另见这些相关的SO问题:

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

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