用JavaScript替换文本时出现问题。请帮忙 function$(id){returndocument.getElementById(id);} $('h').innerHTML.replace(/hello/g,“hello”);

用JavaScript替换文本时出现问题。请帮忙 function$(id){returndocument.getElementById(id);} $('h').innerHTML.replace(/hello/g,“hello”);,javascript,Javascript,它不起作用。发生了什么?替换()未在适当位置发生;您需要将结果分配到所需的目标: function $(id) { return document.getElementById(id); } $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>"); var newText=$('h').innerHTML.replace(/hello/g,“hello”); //用new

它不起作用。发生了什么?

替换()未在适当位置发生;您需要将结果分配到所需的目标:

function $(id) { return document.getElementById(id); }

$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
var newText=$('h').innerHTML.replace(/hello/g,“hello”);
//用newText做点什么
替换()未在适当位置发生;您需要将结果分配到所需的目标:

function $(id) { return document.getElementById(id); }

$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
var newText=$('h').innerHTML.replace(/hello/g,“hello”);
//用newText做点什么

replace
返回字符串,不会自动将其分配给元素

var newText = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
// Do something with newText
$('h').innerHTML=$('h').innerHTML.replace(/hello/g,“hello”);

replace
返回字符串,不会自动将其分配给元素

var newText = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
// Do something with newText
$('h').innerHTML=$('h').innerHTML.replace(/hello/g,“hello”);

首先,您不需要第一个函数,JQuery会通过选择器自动处理这些函数。另外,不管怎样,设置innerHTML应该替换它的所有现有内容,因此不需要在此之后显式地声明replace

$('h').innerHTML = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
$('h').html(/hello/g,“hello”);

另外,我认为您的引用是错误的。

首先,您不需要使用第一个函数,JQuery通过选择器自动处理这个问题。另外,不管怎样,设置innerHTML应该替换它的所有现有内容,因此不需要在此之后显式地声明replace

$('h').innerHTML = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
$('h').html(/hello/g,“hello”);

另外,我认为您的引用是错误的。

您没有将值赋回元素

您没有将值赋回元素

尝试这样做:

$('#h').html(/hello/g, "<span style='color: red;'>hello</span>");
function$(id){returndocument.getElementById(id);}
$('h').innerHTML=$('h').innerHTML.replace(“你好”,“你好”);
小提琴:

试着这样做:

$('#h').html(/hello/g, "<span style='color: red;'>hello</span>");
function$(id){returndocument.getElementById(id);}
$('h').innerHTML=$('h').innerHTML.replace(“你好”,“你好”);

fiddle:

ummm您有一个id=h的html元素?ummm您有一个id=h的html元素?