我如何优化此Javascript代码以对其进行优化,使其仅适用于图像的链接(而不适用于文本的链接) [英] How can I refine this Javascript code to refine it so it only work on links from images (and NOT links from text)

查看:98
本文介绍了我如何优化此Javascript代码以对其进行优化,使其仅适用于图像的链接(而不适用于文本的链接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对现在,它代替作用于所有链接,我能否仅查看来自图像的链接?

Now, instead of it acting on all links, can I get it to only look at links that are from images?

下面是一个HTML代码段,用于显示我的意思:

Here is an HTML snippet to show what I mean:

<a href="/shop/product?ie=UTF8&amp;asin=Z00FDLN878&amp;tab=UK_Default" target="_blank"><img width="125" height="125" border="0" src="http://ecx.images-amazon.com/images/I/01W9a7gwosL.jpg" alt="43453"></a>

这是图像链接-我希望它对此起作用.

That's an image link - I do want it to act on that.

我的直觉是代码实际上是不可能的-因为document.getElementsByTagName('a')无法看到文本链接和图像链接之间的区别.

My gut instinct is that this isn't actually possible in code - because document.getElementsByTagName('a') can't see the difference between a text link and an image link.

推荐答案

使用

Use querySelectorAll to pre-select only the right kinds of nodes. EG:

// the new base url
var base        = 'https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linkImgs    = document.querySelectorAll ("a > img");

for (var J = linkImgs.length - 1;  J >= 0;  --J) {
    var imgLink = linkImgs[J].parentNode;

    //--- Check each link for the 'asin' value
    var result  = /asin=([\d\w]+)/.exec (imgLink.getAttribute ('href') );
    if( result) {
        // make a new url using the 'base' and the 'asin' value
        imgLink.setAttribute ('href', base+result[1]);
    }
}

这篇关于我如何优化此Javascript代码以对其进行优化,使其仅适用于图像的链接(而不适用于文本的链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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