简体   繁体   English

无法用JavaScript替换文本。 请帮忙

[英]Trouble replacing text with JavaScript. Please help

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; replace()不会就地发生; 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. 首先,您不需要第一个函数,JQuery会通过选择器自动进行处理。 Also, setting innerHTML should replace all the existing content of it anyway, so you don't need to explicitly state replace after that. 另外,设置innerHTML仍应替换其所有现有内容,因此您无需在此之后显式声明replace。

$('#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>");

fiddle: http://jsfiddle.net/maniator/LBAn6/ 小提琴: http//jsfiddle.net/maniator/LBAn6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM