我是 JavaScript 的新手,我正在尝试制作一个 Greasemonkey 脚本,用实际图像替换图像链接(以及我稍后会做的其他事情)。
所以我想我可以使用以下内容。
var imagelinks = [
"http*://*/*.jpg",
"http*://*/*.png",
"http*://*/*.gif"
];
我想做的就是使用 JavasScript(和/或 jQuery),将“post-list-content-element”元素中的原始 URL 文本替换为该 URL 链接到的图像。在 this example我想用实际图像替换该 URL。
最佳答案
感谢您将示例链接添加到您的问题,它真的很有帮助。我已经删除了我以前的困惑努力。
var items = document.getElementsByClassName('post-list-content-element');
[].forEach.call(items, function(item){
item.innerHTML = item.innerHTML.replace(
/http?:\/\/\S*?\.(jpg|png|gif)/g,
'<img src=$&>');
});
注意:这假设您的 post-list-content-element
div 中没有实际图像。
好的,这是一个更通用的版本,它只在文本节点内进行替换。我会让你解决错误:-)
var replaceInChildTextNodes = (function(){
var eachChild, splits;
eachChild = function(node, f){
var children, parent = node;
children = [].slice.apply(parent.childNodes);
children.forEach(function(child){
f(child, parent);
eachChild(child, f);
});
};
splits = function(s, regexp){
var nonmatches=[], matches=[], i=0, j=0;
while((match = regexp.exec(s))){
j = match.index;
nonmatches.push(s.substr(i, j-i));
matches.push(match[0]);
i = j + match[0].length;
if(!regexp.global)
break;
}
nonmatches.push(s.substr(i));
return {nonmatches: nonmatches, matches: matches};
};
return function(nodes, regexp, replacer){
[].forEach.call(nodes, function(node){
eachChild(node, function(childNode, parent){
var match, i=0, j=0, split, newNodes=[];
if(childNode.nodeName === '#text'){
split = splits(childNode.nodeValue, regexp);
if(split.matches.length === 0)
return;
newNodes = [];
split.nonmatches.forEach(function(text, i){
if(text !== '')
newNodes.push(document.createTextNode(text));
if(split.matches[i])
newNodes.push(replacer(split.matches[i]));
});
newNodes.forEach(function(newNode){
parent.insertBefore(newNode, childNode);
});
parent.removeChild(childNode);
}
});
});
};
}());
用法:
var parents = document.getElementsByClassName('post-list-content-element');
replaceInChildTextNodes(parents, /http?:\/\/\S*?\.(jpg|png|gif)/g, function(text){
var img = document.createElement('img');
img.src = text;
return img;
});
它不使用 String#split,因此您无需担心在正则表达式中捕获组,它尊重 g
标志。
警告:不能跨浏览器。
关于javascript - 如何使用 JavaScript 将文本节点中的纯文本图像 URL 替换为 img 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8546821/