jQuery text() 和 replace() 不会替换文本 [英] jQuery text() with replace() doesn't replace the text

查看:19
本文介绍了jQuery text() 和 replace() 不会替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 H2:

<h2 id="resetPWSuccess">Password reset instructions have been sent to *|RESETPASSWORDEMAIL|*</h2>

我想将 *|RESETPASSWORDEMAIL|* 替换为我在 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.

推荐答案

改用这个:

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

这篇关于jQuery text() 和 replace() 不会替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆