带有replace()的jQuery文本()不会替换文本 [英] jQuery text() with replace() doesn't replace the text
问题描述
我有以下H2:
I have the following H2:
<h2 id="resetPWSuccess">Password reset instructions have been sent to *|RESETPASSWORDEMAIL|*</h2>
我想替换 * | RESETPASSWORDEMAIL | * $ c $我用jQuery变量
emailAddress
。
I want to replace the *|RESETPASSWORDEMAIL|*
with current email address that I have in the jQuery variable emailAddress
.
具有当前的电子邮件地址。无效:
I have tried the following but it doesn't work:
$('h2#resetPWSuccess').text().replace('*|RESETPASSWORDEMAIL|*', emailAddress).show();
有没有办法更新h2文本 - 如果可能,我更喜欢一行。
Is there a way to update the h2 text - I prefer one line if possible.
推荐答案
使用此代替:
Use this instead :
$('#resetPWSuccess').text(
$('#resetPWSuccess').text().replace('*|RESETPASSWORDEMAIL|*', emailAddress)
).show();
请注意,我也删除了 h2
从你的选择器:这是没用的,比只使用id慢。当您要求jQuery搜索 #resetPWSuccess
时,它使用非常快速的本地 getElementById
函数。
Note that I also removed the h2
from your selector : it's useless and slower than just using the id. When you ask jQuery to search for #resetPWSuccess
, it uses the very fast native getElementById
function.
从jQuery的源代码:
From jQuery's source code :
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
这篇关于带有replace()的jQuery文本()不会替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!