In today's world where B/S structure clients are becoming more and more "fat", as a full-end programmer, you are likely to operate html strings on the front end. Note that you are operating html strings, not the current page. html.
For example, Ueditor, an online HTML rich text editor launched by Baidu, can create rich text documents online, and its functions are comparable to a streamlined version of Microsoft Word. Although Ueditor has the aura of Baidu, the actual effect is not very satisfactory. We need to process the html string it generates twice, such as setting the width of all images to 90%.
Through a certain method, we can get the html string in the text editor. Assume that the string is as follows:
Flower-like Sao Nian
Mysterious Pyramid
A dream-like life
But what to do next? The elegant processing of strings makes it easy for us to think of regular expressions. Can we use regular expressions here?
The answer is yes, try the regular effect first. Set the width of all images to 90%. The simplest way is to add the style attribute to the img tag and then specify the width in style.
Using regular rules, the first step is to match all img tags. Since the img tag does not necessarily have a style attribute, you must first determine whether there is a style attribute, and then directly add width: 90%; to the style attribute? No, this may overwrite other original attributes, so just add them directly. The addition will not overwrite them! Still not working, what if there is width originally. . .
I haven’t started writing regular expressions yet. Thinking about the process first, it is already very tedious. In fact, the implementation is even more complicated.
Fortunately, we can change our thinking and solve this problem with the help of jQuery.
The power of jQuery is that it can directly package an HTML string into a dom element. This dom element does not exist in the current page, it is placed in memory.
Through jQuery, you only need this piece of code:
The comments in the code are very detailed, so I won’t explain too much. We need to understand that jQuery can not only operate the html in the real page, but also the virtual html in the memory.
By comparing the two, I believe readers can immediately understand which method is better.
As Xiao Cai often says: If you think a problem can be solved, but it still hasn’t been solved after a long time, it’s probably that your thinking is wrong. Think about it from another angle, and the problem will be solved!