简体   繁体   English

如何使用JavaScript在锚点之前插入元素

[英]how insert element before anchor using javascript

function Insert_Icon() {
 var images = document.images;
 for (var i=0; i<images.length; i++){
    if (images[i].parentNode.tagName.toLowerCase()=='a') {
         var re = new RegExp("google\.com","ig");
        if (re.test(images[i].parentNode.href)){

            alert(images[i].parentNode.href);
        }
      /*  ---need insert this element before anchor----
       var currentElement = document.createElement("img");  
      currentElement.setAttribute("class", "icone"); 
      currentElement.setAttribute("src", "images/google.png"); */ 

    }
 }
}

all images with hyperlink for google show my png, try insertBefore but unsuccessfully Google带有超链接的所有图像都显示我的png,请尝试insertBefore但未成功

like this 像这样

<img class="icone" src="images/google.png"/><a href="http://google.com" target="_self"> <img class="cover_imagem" src="cover/2.jpg"</a>

I understand that this is not exactly the answer to your question, but you could try using css. 我了解这并不是您所提问题的确切答案,但是您可以尝试使用CSS。 This will not work in all browsers, however. 但是,这并非在所有浏览器中都适用。

a[href^="http://google.com"]:before {
    content: url(http://g.etfv.co/http://www.google.com);
}

http://jsfiddle.net/kaleb/vbVck/ http://jsfiddle.net/kaleb/vbVck/

Using JavaScript to perform this operation in a loop will cause many redraws which can kill performance and perceived performance of your webpage. 使用JavaScript循环执行此操作将导致许多重绘,这可能会破坏网页的性能和可感知的性能。 Ideally, you would use something like Modernizr to test if the user's browser supports these features and do the JS fallback only when necessary. 理想情况下,您将使用Modernizr之类的工具来测试用户的浏览器是否支持这些功能,并仅在必要时执行JS回退。

If you're saying the <img> needs to be removed from its parent <a> , and inserted before that <a> , then do this: 如果您说<img>需要从其父<a>删除,并在该<a>之前插入,请执行以下操作:

 // parent of <a>--------v    the <img>---------v   the <a>----------v
images[i].parentNode.parentNode.insertBefore( images[i], images[i].parentNode );

This invokes insertBefore on the parentNode of the <a> (that is the parentNode of the <img> ) and inserts the <img> before the <a> . 这将调用insertBefore上的parentNode <a> (即的所述parentNode <img>并插入<img>的前<a>

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

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