如何使用JavaScript在锚点之前插入元素 [英] how insert element before anchor using javascript

查看:45
本文介绍了如何使用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"); */ 

    }
 }
}

带有Google超级链接的所有图像均显示我的png,请尝试insertBefore但未成功

all images with hyperlink for google show my png, try insertBefore but unsuccessfully

像这样

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


推荐答案

我了解这并非您的确切答案问题,但您可以尝试使用CSS。

I understand that this is not exactly the answer to your question, but you could try using 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/

使用JavaScript循环执行此操作会导致许多重绘会破坏您的网页性能和感知性能。理想情况下,您可以使用 Modernizr 之类的东西来测试用户的浏览器是否支持这些功能,并且仅在以下情况下执行JS后备功能:

Using JavaScript to perform this operation in a loop will cause many redraws which can kill performance and perceived performance of your webpage. 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.

这篇关于如何使用JavaScript在锚点之前插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆