我想用一個鏈接替換頁面上各處的括號文本。我知道這可以通過php/etc來完成,但我可以包含這個腳本,以便能夠簡單地包含並處理替換本身。使用JS來改變括號內的文本鏈接到指定的頁面
例如:
如果[頁= 12]在頁內發現我想將其鏈接到: 將其改爲: http://www.example.com/pages/12(可點擊的鏈接)。
謝謝!
我想用一個鏈接替換頁面上各處的括號文本。我知道這可以通過php/etc來完成,但我可以包含這個腳本,以便能夠簡單地包含並處理替換本身。使用JS來改變括號內的文本鏈接到指定的頁面
例如:
如果[頁= 12]在頁內發現我想將其鏈接到: 將其改爲: http://www.example.com/pages/12(可點擊的鏈接)。
謝謝!
這個工程,我在註釋中描述:
var stack = [Array.prototype.slice.call(document.getElementsByTagName("body")[0].childNodes)], nodes, node, parent, text, offset;
while (stack.length) {
nodes = stack.pop();
for (var i=0, n=nodes.length; i<n; ++i) {
node = nodes[i];
switch (node.nodeType) {
case Node.ELEMENT_NODE:
if (node.nodeName.toUpperCase() !== "SCRIPT") {
stack.push(Array.prototype.slice.call(node.childNodes));
}
break;
case Node.TEXT_NODE:
text = node.nodeValue;
offset = text.indexOf("[page=");
if (offset >= 0 && text.substr(offset).match(/^(\[page=(\d+)\])/)) {
parent = node.parentNode;
var before = document.createTextNode(text.substr(0, offset));
link = document.createElement("a"),
after = document.createTextNode(text.substr(offset + RegExp.$1.length));
link.appendChild(document.createTextNode(text.substr(offset, RegExp.$1.length)));
link.setAttribute("href", "http://www.example.com/pages/" + RegExp.$2);
parent.insertBefore(after, node);
parent.insertBefore(link, after);
parent.insertBefore(before, link);
parent.removeChild(node);
stack.push([after]);
}
}
}
}
text.replace(/\[page=(\w+)\]/g, '<a href="http://example/pages/$1">http://example/pages/$1</a>')
至於在網頁中找到無處不在,你真的不希望這樣做。
這裏有一個正則表達式來做到這一點:
var str = "This is a link: [page=12]"
str = str.replace(/\[page=([^\]]*)\]/g,
'<a href="www.example.com/pages/$1">www.example.com/pages/$1</a>');
這將匹配[頁碼=測試]爲好。
這不是那麼容易,你可能認爲。使用'innerHTML'可能會很慢,並且使用DOM操作很棘手,因爲您需要用三個新節點(文本,A元素,文本)替換文本節點。 – Gumbo 2009-10-01 14:26:18
您是否使用任何js框架? 這不是更多的PHP的事情嗎? – Eric 2009-10-01 14:28:23
我正在使用jQuery。是的,我知道明顯的解決方案是使用PHP,但不幸的是,因爲它必須安裝幾個不同的網站,有些我不直接控制,我想盡可能簡單。只需要它們包含一個JS文件。 – Rob 2009-10-01 14:31:22