function $(id) { return document.getElementById(id); }
$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
It doesn't work. What happened?
replace
返回一个字符串,并且不会自动将其分配给元素。
$('h').innerHTML = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
replace() does not happen in-place; you need to assign the result to the destination you want:
var newText = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
// Do something with newText
First of all, you don't need your first function, JQuery takes care of that automatically via a selector. Also, setting innerHTML should replace all the existing content of it anyway, so you don't need to explicitly state replace after that.
$('#h').html(/hello/g, "<span style='color: red;'>hello</span>");
Also, I think your quotes were wrong.
您没有将值分配回元素。
Try doing this:
function $(id) { return document.getElementById(id); }
$('h').innerHTML = $('h').innerHTML.replace("hello", "<span style='color: red;'>hello</span>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.