Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery:replace()在html()中_Jquery_Html_Replace - Fatal编程技术网

jQuery:replace()在html()中

jQuery:replace()在html()中,jquery,html,replace,Jquery,Html,Replace,如何将html部分替换为replace() 我猜html()与text()的工作原理不一样 测试:使用g开关使您的模式成为全局模式: var e = $("div"), fix = e.html().replace(/google.com/g, "duckduckgo.com"); e.html(fix); 这样它就替换了链接和文本。问题在于.replace只替换第一次出现的内容。如果要替换所有事件,必须使用带有g(全局)标志的正则表达式: var e=$(“div”), fix=e.ht

如何将html部分替换为
replace()

我猜html()与
text()的工作原理不一样


测试:

使用
g
开关使您的模式成为全局模式:

var e = $("div"),
fix = e.html().replace(/google.com/g, "duckduckgo.com");
e.html(fix);


这样它就替换了链接和文本。

问题在于
.replace
只替换第一次出现的内容。如果要替换所有事件,必须使用带有
g
(全局)标志的正则表达式:

var e=$(“div”),
fix=e.html().replace(/google\.com/g,“duckduckgo.com”);
e、 html(fix)


jsfiddle

使您的正则表达式全局化,OP根本不使用正则表达式;)哦!
replace()
只吃regex:/@j08691,很抱歉给你添麻烦,但他没有使用模式。别误会我,谢谢。保存
replaceAll()
以防万一:)但这不会替换链接的
href
属性。
var e = $("div"),
    fix = e.html().replace("google.com", "duckduckgo.com");
e.html(fix);
var e = $("div"),
fix = e.html().replace(/google.com/g, "duckduckgo.com");
e.html(fix);
$("div a").attr("href", function (i, o) {
    return (/google/.test(o) ? "http://duckduckgo.com" : o)
}).html($("a", this).attr("href").substr(7))