동일한 "id"를 가진 여러 요소가있을 때 jQuery는 어떻게 작동합니까?
동일한 .NET Framework를 포함하는 여러 요소가있는 Google의 애드워즈 웹 사이트에서 데이터를 가져옵니다 id
.
다음 3 개의 쿼리가 동일한 답변 (2)을 얻지 못하는 이유를 설명해 주시겠습니까?
HTML :
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS :
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
동일한 ID를 가진 2 개의 요소를 갖는 것은 W3C 사양에 따라 유효한 html이 아닙니다.
CSS 선택기에 ID 선택 자만 있고 특정 컨텍스트에서 사용되지 않는 경우 jQuery는 document.getElementById
해당 ID가있는 첫 번째 요소 만 반환 하는 기본 메서드를 사용합니다 .
그러나 다른 두 인스턴스에서 jQuery는 Sizzle 선택기 엔진 (또는 querySelectorAll
사용 가능한 경우) 에 의존하며 두 요소를 모두 선택합니다. 결과는 브라우저별로 다를 수 있습니다.
그러나 동일한 페이지에 동일한 ID를 가진 두 요소가 있어서는 안됩니다. CSS에 필요한 경우 대신 클래스를 사용하십시오.
반드시 중복 ID로 선택해야하는 경우 속성 선택기를 사용하십시오.
$('[id="a"]');
바이올린 살펴보기 : http://jsfiddle.net/P2j3f/2/
참고 : 가능한 경우 다음과 같이 태그 선택기로 해당 선택기를 한정해야합니다.
$('span[id="a"]');
주어진 ID를 가진 요소는 하나만 있어야합니다. 그 상황에 갇혀 있다면 옵션에 대한 내 대답의 후반부를 참조하십시오.
동일한 ID (불법 HTML)를 가진 여러 요소가있을 때 브라우저가 작동하는 방식은 사양에 정의되어 있지 않습니다. 모든 브라우저를 테스트하고 작동 방식을 알아낼 수 있지만이 구성을 사용하거나 특정 동작에 의존하는 것은 현명하지 않습니다.
여러 개체가 동일한 식별자를 갖도록하려면 클래스를 사용하십시오.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
문서를 수정할 수 없기 때문에 동일한 ID를 가진 요소를 안정적으로보고 싶다면 내장 된 DOM 함수에 의존 할 수 없기 때문에 자체 반복을 수행해야합니다.
다음과 같이 할 수 있습니다.
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
또는 jQuery 사용 :
$("div *").filter(function() {return(this.id == "a");});
jQuery 작업 예 : http://jsfiddle.net/jfriend00/XY2tX/ .
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a
and if so, just used document.getElementById("a")
. If the selector is more complex than that and querySelectorAll()
exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll()
does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll()
implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
jQuery's id
selector only returns one result. The descendant
and multiple
selectors in the second and third statements are designed to select multiple elements. It's similar to:
Statement 1
var length = document.getElementById('a').length;
...Yields one result.
Statement 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
Statement 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html>
and <body>
tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
console.log($('span#a').length);
try JSfiddle: https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/
Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId
'developer tip' 카테고리의 다른 글
정적 메서드 모의 (0) | 2020.11.15 |
---|---|
boost :: shared_ptr 사용에서 std :: shared_ptr로 전환해야합니까? (0) | 2020.11.15 |
루프 내에서 함수를 만들지 마십시오. (0) | 2020.11.15 |
리눅스 / proc / loadavg (0) | 2020.11.15 |
첫 번째 명령을 일시 중단하더라도 (Ctrl-z) 명령을 하나씩 실행합니다. (0) | 2020.11.15 |