JavaScript 또는 jQuery에서 HTML을 정규화하는 방법은 무엇입니까?
태그는 여러 속성을 가질 수 있습니다. 코드에서 속성이 나타나는 순서는 중요하지 않습니다. 예를 들면 :
<a href="#" title="#">
<a title="#" href="#">
Javascript에서 HTML을 "정규화"하여 속성의 순서가 항상 동일하도록하려면 어떻게해야합니까? 항상 같은 순서라면 어떤 순서를 선택하든 상관 없습니다.
업데이트 : 내 원래 목표는 약간의 차이가있는 2 개의 HTML 페이지를 (자바 스크립트에서) 쉽게 비교하는 것이 었습니다. 사용자가 다른 소프트웨어를 사용하여 코드를 편집 할 수 있기 때문에 속성의 순서가 변경 될 수 있습니다. 이것은 diff를 너무 장황하게 만듭니다.
답변 : 먼저 모든 답변에 감사드립니다. 그리고 예, 가능합니다. 내가 그것을 어떻게 관리했는지는 다음과 같습니다. 이것은 개념 증명이며 확실히 최적화 할 수 있습니다.
function sort_attributes(a, b) {
if( a.name == b.name) {
return 0;
}
return (a.name < b.name) ? -1 : 1;
}
$("#original").find('*').each(function() {
if (this.attributes.length > 1) {
var attributes = this.attributes;
var list = [];
for(var i =0; i < attributes.length; i++) {
list.push(attributes[i]);
}
list.sort(sort_attributes);
for(var i = 0; i < list.length; i++) {
this.removeAttribute(list[i].name, list[i].value);
}
for(var i = 0; i < list.length; i++) {
this.setAttribute(list[i].name, list[i].value);
}
}
});
Same thing for the second element of the diff, $('#different')
. Now $('#original').html()
and $('#different').html()
show HTML code with attributes in the same order.
JavaScript doesn't actually see a web page in the form of text-based HTML, but rather as a tree structure known as the DOM, or Document Object Model. The order of HTML element attributes in the DOM is not defined (in fact, as Svend comments, they're not even part of the DOM), so the idea of sorting them at the point where JavaScript runs is irrelevant.
I can only guess what you're trying to achieve. If you're trying to do this to improve JavaScript/page performance, most HTML document renderers already presumably put a lot of effort into optimising attribute access, so there's little to be gained there.
If you're trying to order attributes to make gzip compression of pages more effective as they're sent over the wire, understand that JavaScript runs after that point in time. Instead, you may want to look at things that run server-side instead, though it's probably more trouble than it's worth.
Take the HTML and parse into a DOM structure. Then take the DOM structure, and write it back out to HTML. While writing, sort the attributes using any stable sort. Your HTML will now be normalized with regard to attributes.
This is a general way to normalize things. (parse non-normalized data, then write it back out in normalized form).
I'm not sure why you'd want to Normalize HTML, but there you have it. Data is data. ;-)
This is a proof of concept, it can certainly be optimized:
function sort_attributes(a, b) {
if( a.name == b.name) {
return 0;
}
return (a.name < b.name) ? -1 : 1;
}
$("#original").find('*').each(function() {
if (this.attributes.length > 1) {
var attributes = this.attributes;
var list = [];
for(var i =0; i < attributes.length; i++) {
list.push(attributes[i]);
}
list.sort(sort_attributes);
for(var i = 0; i < list.length; i++) {
this.removeAttribute(list[i].name, list[i].value);
}
for(var i = 0; i < list.length; i++) {
this.setAttribute(list[i].name, list[i].value);
}
}
});
Same thing for the second element of the diff, $('#different'). Now $('#original').html() and $('#different').html() show HTML code with attributes in the same order.
you can try open HTML tab in firebug, the attributes are always in same order
Actually, I can think of a few good reasons. One would be comparison for identity matching and for use with 'diff' type tools where it is quite annoying that semantically equivalent lines can be marked as "different".
The real question is "Why in Javascript"?
This question "smells" of "I have a problem and I think I have an answer...but I have a problem with my answer, too."
If the OP would explain why they want to do this, their chances of getting a good answer would go up dramatically.
The question "What is the need for this?" Answer: It makes the code more readable and easier to understand.
Why most UI sucks... Many programmers fail to understand the need for simplifying the users job. In this case, the users job is reading and understanding the code. One reason to order the attributes is for the human who has to debug and maintain the code. An ordered list, which the program becomes familiar with, makes his job easier. He can more quickly find attributes, or realize which attributes are missing, and more quickly change attribute values.
This only matters when someone is reading the source, so for me it's semantic attributes first, less semantic ones next...
There are exceptions of course, if you have for example consecutive <li>'s, all with one attribute on each and others only on some, you may want to ensure the shared ones are all at the start, followed by individual ones, eg.
<li a="x">A</li>
<li a="y" b="t">B</li>
<li a="z">C</li>
(Even if the "b" attribute is more semantically useful than "a")
You get the idea.
it is actually possible, I think, if the html contents are passed as xml and rendered through xslt... therefore your original content in XML can be in whatever order you want.
참고URL : https://stackoverflow.com/questions/3974734/how-to-normalize-html-in-javascript-or-jquery
'developer tip' 카테고리의 다른 글
Gradle로 JaCoCo 커버리지 보고서 필터링 (0) | 2020.09.22 |
---|---|
Java의 ByteBuffer에서 바이트 배열을 가져옵니다. (0) | 2020.09.22 |
Rails 4에서 컨트롤러 또는 액션에 대한 X-Frame-Options를 재정의하는 방법 (0) | 2020.09.22 |
배열에서 스트리밍 할 때 정수를 문자열에 매핑 할 수없는 이유는 무엇입니까? (0) | 2020.09.22 |
Makefile ifeq 논리적 또는 (0) | 2020.09.22 |