Today, when 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 characters. String, not the html of the current page.
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 the string is as follows:
1 <p>花一样的骚年</p>2 <img src="./saonian.png" alt="骚年自拍" >3 <p>迷一样的金字塔</p>4 <img style="height:30px;" src="./jinzita.png" alt="中国金字塔" >5 <p>梦一样的人生</p>6 <img style="width:50px;height:30px;" src="./rensheng.png" alt="人生百态" >
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 wrap an HTML string into a dom element. This dom element does not exist in the current page, it is placed in memory.
1 //定义容器,方便获取修改后的html字符串 2 //直接用jQuery包装"<div></div>",此时在内存中就有了一个div元素 3 var $container = $("<div></div>"); 4 //假设这是需要修改的html字符串 5 var html = "<img style='width: 50%;' src='./test.jpg' >"; 6 //直接将要修改的html字符串插入到容器中 7 //jQuery强大到自动将html字符串包装成dom元素,然后插入到内存中的div容器中 8 $container.append(html); 9 //在容器中搜索所有的img标签,并遍历10 $container.find("img").each(function(i,n){11 //对于每一个img元素,直接修改其style属性中的width属性12 //如果style属性没有,自动添加;如果已经有width属性,直接修改;完全不用过多操心13 $(n).css({14 width: "90%"15 });16 });17 //获取修改后的html字符串,即容器的html内容18 alert($container.html());
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!