Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

html - jQuery text() with replace() doesn't replace the text

I have the following H2:

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

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();

Is there a way to update the h2 text - I prefer one line if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this instead :

$('#resetPWSuccess').text(
   $('#resetPWSuccess').text().replace('*|RESETPASSWORDEMAIL|*', emailAddress)
).show();

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.

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...