function $(id) { return document.getElementById(id); }
$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
它不起作用。發生了什麼?無法用JavaScript取代文字。請幫助
function $(id) { return document.getElementById(id); }
$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
它不起作用。發生了什麼?無法用JavaScript取代文字。請幫助
replace()不會在原地發生;您需要將結果分配給你想要的目的地:
var newText = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
// Do something with newText
replace
返回一個字符串,並不會自動將其分配到的元素。
$('h').innerHTML = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
+1你們對我來說太快了! – Tejs 2011-05-11 18:44:39
首先,你不需要你的第一個函數,JQuery通過選擇器自動處理它。此外,設置innerHTML應該取代它的所有現有內容,因此您不需要在此之後明確指出替換狀態。
$('#h').html(/hello/g, "<span style='color: red;'>hello</span>");
此外,我認爲你的報價是錯誤的。
您不會將值分配回元素。
試着這樣做:
function $(id) { return document.getElementById(id); }
$('h').innerHTML = $('h').innerHTML.replace("hello", "<span style='color: red;'>hello</span>");
嗯,你有ID = h的html元素? – Neal 2011-05-11 18:42:18