如何做一个;简单的;在jQuery中查找和替换?
我是jquery新手,在执行我认为应该是非常简单的查找和替换操作时遇到了困难 我想更改“”标记内的文本。例如,我可能想用“标题”替换“你的标题” 我真的看不出我做错了什么,有什么想法吗 请帮忙,谢谢试试这个如何做一个;简单的;在jQuery中查找和替换?,jquery,string,replace,Jquery,String,Replace,我是jquery新手,在执行我认为应该是非常简单的查找和替换操作时遇到了困难 我想更改“”标记内的文本。例如,我可能想用“标题”替换“你的标题” 我真的看不出我做错了什么,有什么想法吗 请帮忙,谢谢试试这个 $(function() { var text = $('#ValidationSummary').text().replace("title", "your title"); // this will give the text after replacement, but it
$(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);
};
$('#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"));
对JS中字符串的任何更改都会生成一个新字符串,而不是修改原来的字符串。幸运的是,jQuery可以轻松地同时检索和修改文本:
$('#ValidationSummary p').text(function (i, old) {
return old
.replace('your title', 'a title')
.replace('first name', 'christian name')
.replace('your surname', 'your last name');
});
说明:
从return
中提取一个字符串,告诉jQuery用这个新字符串替换那里的内容(作为.text()
传递)旧的
- 由于
每次都返回一个新字符串,因此我们可以将多个调用链接在一起,这样我们只需要一个replace()
调用和.text()
语句return
- 我使用了选择器
,因为使用“#ValidationSummary p”
或.text()
将替换它所操作的元素的全部内容.html()
- 打开
工作正常,但不认为可靠。非常感谢,这几乎是完美的,但被接受的答案是完美的。text()不应该这样使用,它应该是:$(“#ValidationSummary”).text($(this).text().replace(“你的标题”,“一个标题”);
$('#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"));
$('#ValidationSummary p').text(function (i, old) {
return old
.replace('your title', 'a title')
.replace('first name', 'christian name')
.replace('your surname', 'your last name');
});
$(function() {
$('#ValidationSummary').html($('#ValidationSummary').html().replace("title", "Mister"));
$('#ValidationSummary').html($('#ValidationSummary').html().replace("first name", "ABC"));
$('#ValidationSummary').html($('#ValidationSummary').html().replace("surname", "XYZ"));
});