How to do a "simple" find and replace in jQuery?
I am new to jquery, and I'm having trouble doing what I thought should be a very simple find and replace operation.
I want to change the text inside the the "<p>" tags. So for instance I might want to rep开发者_开发知识库lace "your title" with "a title".
<div id="ValidationSummary">
<ul>
<li>
<p>
Please specify your title</p>
</li>
<li>
<p>
Please enter your first name</p>
</li>
<li>
<p>
Please enter your surname</p>
</li>
</ul>
</div>
and here is the jQuery which isn't doing anything:
$(function() {
$('#ValidationSummary').text().replace("your title", "a title");
$('#ValidationSummary').text().replace("first name", "christian name");
$('#ValidationSummary').text().replace("your surname", "your last name");
};
I really cannot see what I'm doing wrong, any ideas?
Please help, thanks
Any changes to strings in JS always produces a new string, rather than modifying what was there. Fortunately jQuery makes it easy to both retrieve and modify text at the same time:
$('#ValidationSummary p').text(function (i, old) {
return old
.replace('your title', 'a title')
.replace('first name', 'christian name')
.replace('your surname', 'your last name');
});
Explanation:
return
ing a string from.text()
tells jQuery to replace what was there (passed in asold
) with this new string.Since
replace()
returns a new string each time, we can chain multiple calls together, so that we only need one.text()
call andreturn
statement.I used the selector
'#ValidationSummary p'
since using.text()
or.html()
will replace the entire contents of the element it is operating on.
$(function() {
var text = $('#ValidationSummary').text().replace("title", "your title"); // this will give the text after replacement, but it will not set the text to ValidationSummary
$('#ValidationSummary').text(text);
text = $('#ValidationSummary').text().replace("first name", "christian name");
$('#ValidationSummary').text(text);
text = $('#ValidationSummary').text().replace("your postcode", "your zipcode");
$('#ValidationSummary').text(text);
};
On JSFIDDLE.
$(function() {
$('#ValidationSummary').html($('#ValidationSummary').html().replace("title", "Mister"));
$('#ValidationSummary').html($('#ValidationSummary').html().replace("first name", "ABC"));
$('#ValidationSummary').html($('#ValidationSummary').html().replace("surname", "XYZ"));
});
Works but don't think it's reliable.
TRY THIS...
$('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("title", "your title"));
$('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("first name", "christian name"));
$('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("your postcode", "your zipcode"));
精彩评论