简体   繁体   English

查找并替换整个html本身中出现的字符串

[英]Find and replace occurrence of string in whole html itself

Assume 假设

<html>  
<head>....</head>
<body>
 .
 .  // Occurrences are here
 .  
</body>
</html>

I do 我做

$(function()
{
    $('html').html() = $('html').html().replace(/strToFind/g,'somethingElse');
});

in head, but it does't work. 在脑海中,但它不起作用。 How I do to find and replace all occurrence of string in html document itself (not store in variable)? 如何查找和替换html文档本身中所有出现的字符串(而不存储在变量中)?
Thanks 谢谢

.html() is a function that returns the HTML, you can't assign to it. .html()是一个返回HTML的函数,您无法为其分配。 If you want to change the HTML of an object in jQuery, you put the new HTML as a parameter to the function: 如果要在jQuery中更改对象的HTML,请将新的HTML作为函数的参数:

$('html').html($('html').html().replace(/strToFind/g,'somethingElse'));

$('html').html() would return the html string , but won't set it. $('html').html()将返回html字符串,但不会设置它。

You can use this function 您可以使用此功能

function rep_all()
{
    var str = $('html').html();
    str.replace('strtofind','strtoreplace');
    $('html').html(str);
}

.html() is something which writes on the html page it is not like variable so you can't assign anythig to it. .html()是写在html页面上的东西,它不像变量,因此您不能为其分配任何thig。 you need to put the value inside it.like this: 您需要将值放在其中。像这样:

$('html').html( $('html').html().replace(/strToFind/g,'somethingElse'));

see here: http://api.jquery.com/html/ 看到这里: http : //api.jquery.com/html/

It's been answered that the .html() is not assignable, you would have to pass the replaced content as a parameter. 有人回答说.html()是不可分配的,您必须将替换后的内容作为参数传递。

Just to point out, it is very uncommon to replace the whole page's html content. 只是指出,替换整个页面的html内容非常少见。

As you defined that the contents to be replaced are inside the body , you should at least (still not good) target only the body : 当您定义要替换的内容在body内部时,您至少(仍然不好)应仅针对body

$('body').html($('body').html().replace(/strToFind/g,'somethingElse'))

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

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