jquery replaces the contents of the selected element ReplaceWith () method
ReplaceWith, replacing elements
This article to introduce jquery ReplaceWith () method of using the method, there is a need to know friends do not enter into the reference, I hope this article to help you students.
The ReplaceWith () method replaces the contents of the selected element with something else.
Let's look at an example first.
The code is as follows |
Copy Code |
<%@ page language= "java" contenttype= "Text/html;charset=utf-8" pageencoding= "UTF-8"% <! DOCTYPE HTML PUBLIC "-//w3c//dtdhtml 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" <meta http-equiv= "Content-type" content= "Text/html;charset=utf-8" <title >inserttitle here</title> <script type= "Text/javascript" src= "Script/jquery-1.7.2.js" ></ Script> <script type= "Text/javascript" $ (document). Ready (function () { $ ("button"). Click (function () { $ ("P"). ReplaceWith ("<b>hello</b>"); //replace contents of P elements with "<b>hello</b>" }); }); </script> <body> <p>1111111111111111111111</p> <button>click</button> </body>
|
Perhaps a lot of friends can not understand, I will introduce the following.
In jquery, there is a powerful replacement function replacewith () that is very simple to use, such as:
The page has the following P tag
Replace all P tags with "# #"
?
1
|
$(
'p'
).replaceWith(
'##'
);
|
Results after execution:
Replace label
With this replacewith, we can replace all P tags with the b tag, and the contents will not change:
1
|
$ (
' P '
function () {
&NBSP;&NBSP;&NBSP;&NBSP;
$" (
this
+$ ( this </b > '
}); /font>
|
Results
That's a replacement!
Multilingual Web sites can be easily completed using this function
If you are developing a multilingual web site, you can even take advantage of this feature, such as adding the I tag to the text you need to translate, and then traversing the translation substitution.
If the page DOM structure is as follows:
We want to translate the text from the I tag in the page to the page where I tag the Apple and the computer . So we need a translation library to implement:
1
2
3
4
|
var
translate = {
&NBSP;&NBSP;&NBSP;&NBSP;
' Apple '
:
' Apple '
&NBSP;&NBSP;&NBSP;&NBSP;
' computer '
' PC '
|
And then I can perform translation substitution like this
1
2
3
|
$(
'i'
).each(
function
(){
$(
this
).replaceWith(translate[$(
this
).html()]);
});
|
Effect after execution:
Page effect:
ReplaceWith and ReplaceAll
Same point: All two of them can be done, find replacement
Different points: The writing is different, anyway, I did not find that their two have any functional differences.
The code is as follows |
Copy Code |
<script type= "Text/javascript" > $ (document). Ready (function () { $ ("strong"). ReplaceAll ($ ("div")); Replace the div tags with the strong tag $ ("div"). ReplaceWith ($ ("strong")); Same as above, no different. }); </script> |