如何优化此Javascript代码,使其从图像中链接到IGNORES [英] How can I refine this Javascript code so it IGNORES links from images
问题描述
{请注意-此问题与过于复杂以至于无法在此处回答}
{Please note - this question is the opposite/inverse of an existing StackOverflow question that is too complex to answer there}
我想对现在,它代替作用于所有链接,我能否只查看来自文本的链接?
Now, instead of it acting on all links, can I get it to only look at links that are from text?
下面是一个HTML代码段,用于显示我的意思:
Here is an HTML snippet to show what I mean:
<a href="/shop/product?ie=UTF8&asin=Z00FDLN878&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 NOT want it to act on that.
推荐答案
在直接javascript/DOM 中,在循环浏览链接时进行测试:
In straight javascript / DOM, test the links as you loop through them:
var base = 'https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linksNoImg = document.querySelectorAll ("a[href*='asin']");
for (var J = linksNoImg.length - 1; J >= 0; --J) {
var imgLink = linksNoImg[J];
//--- Make sure it's not an image link:
if ( ! imgLink.querySelector ('img') ) {
//--- 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]);
}
}
}
jQuery 可让您仅预选择正确的链接:
jQuery lets you preselect only the correct links:
//--- The new base URL
var base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linksNoImg = $("a[href*='asin']:not(:has(img))");
linksNoImg.each ( function () {
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(links[i].getAttribute('href'));
if(result){
// make a new url using the 'base' and the 'asin' value
links[i].setAttribute('href', base+result[1]);
}
} );
但这需要您在Greasekit中加载jQuery-对于最简单的脚本,这是非常值得的.
But this requires you to load jQuery in Greasekit -- which is well worth it for any but the simplest scripts.
这篇关于如何优化此Javascript代码,使其从图像中链接到IGNORES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!