INPUT 태그의 ID 속성을 어떻게 사용할 수 있습니까?
아래 코드에 설명 된 문제에 대한 해결책이 있습니까? 브라우저에서 코드를 필요로하는 내용을 바로 확인하고 원하는 내용을 알기 전에 모든 코드를 살펴볼 수 없습니다.
<html>
<head>
<title>Input ID creates problems</title>
<style type="text/css">
#prologue, #summary { margin: 5em; }
</style>
</head>
<body>
<h1>Input ID creates a bug</h1>
<p id="prologue">
In this example, I make a list of checkboxes representing things which could appear in a book. If you want some in your book, you check them:
</p>
<form>
<ul>
<li>
<input type="checkbox" id="prologue" />
<label for="prologue">prologue</label>
</li>
<li>
<input type="checkbox" id="chapter" />
<label for="chapter">chapter</label>
</li>
<li>
<input type="checkbox" id="summary" />
<label for="summary">summary</label>
</li>
<li>
<input type="checkbox" id="etc" />
<label for="etc">etc</label>
<label>
</li>
</ul>
</form>
<p id="summary">
For each checkbox, I want to assign an ID so that clicking a label checks the corresponding checkbox. The problems occur when other elements in the page already use those IDs. In this case, a CSS declaration was made to add margins to the two paragraphs which IDs are "prologue" and "summary", but because of the IDs given to the checkboxes, the checkboxes named "prologue" and "summary" are also affected by this declaration. The following links simply call a javascript function which writes out the element whose id is <a href="javascript:alert(document.getElementById('prologue'));">prologue</a> and <a href="javascript:alert(document.getElementById('summary'));">summary</a>, respectively. In the first case (prologue), the script writes out [object HTMLParagraphElement], because the first element found with id "prologue" is a paragraph. But in the second case (summary), the script writes out [object HTMLInputElement] because the first element found with id "summary" is an input. In the case of another script, the consequences of this mix up could have been much more dramatic. Now try clicking on the label prologue in the list above. It does not check the checkbox as clicking on any other label. This is because it finds the paragraph whose ID is also "prologue" and tries to check that instead. By the way, if there were another checkbox whose id was "prologue", then clicking on the label would check the one which appears first in the code.
</p>
<p>
An easy fix for this would be to chose other IDs for the checkboxes, but this doesn't apply if these IDs are given dynamically, by a php script for example.
Another easy fix for this would be to write labels like this:
<pre>
<label><input type="checkbox" />prologue</label>
</pre>
and not need to give an ID to the checkboxes. But this only works if the label and checkbox are next to each other.
</p>
<p>
Well, that's the problem. I guess the ideal solution would be to link a label to a checkboxe using another mechanism (not using ID). I think the perfect way to do this would be to match a label to the input element whose NAME (not ID) is the same as the label's FOR attribute. What do you think?
</p>
</body>
</html>
가장 좋은 방법은 접두사를 추가하여 모든 이름을 바꾸는 것입니다. input
<ul>
<li>
<input type="checkbox" id="input_prologue" />
<label for="input_prologue">prologue</label>
</li>
<li>
<input type="checkbox" id="input_chapter" />
<label for="input_chapter">chapter</label>
</li>
<li>
<input type="checkbox" id="input_summary" />
<label for="input_summary">summary</label>
</li>
<li>
<input type="checkbox" id="input_etc" />
<label for="input_etc">etc</label>
</li>
</ul>
이렇게하면 페이지의 다른 ID와 충돌하지 않는 레이블을 클릭하면 특별한 자바 펼쳐 기능없이 전환됩니다.
여기에서 해결되었습니다 : https://stackoverflow.com/a/8537641 그냥 이렇게 해
<label><input type="checkbox">Some text</label>
편집 : 돌이켜 보면 내 솔루션은 이상적이지 않습니다. 대신 다음 답변에 표시된 것처럼 "암시 적 레이블 연결"을 활용하는 것이 좋습니다. stackoverflow.com/a/8537641/884734
내가 제안한 이상적이지 않은 솔루션은 다음과 같습니다.
이 문제는 약간의 자바 스크립트로 쉽게 해결할 수 있습니다. 페이지의 js 파일 중 하나에 다음 코드를 던져 <label>
태그에 다음 동작 을 제공 하십시오.
라벨을 클릭하면 :
id
레이블 for
속성 과 일치 하는 요소가 페이지에있는 경우 기본 기능으로 되돌리고 해당 입력에 초점을 맞 춥니 다.
일치를 사용하여 발견되지 않은 경우 id
,의 형제에 대한 모습 label
A를 class
일치 label
의 for
속성을하고 초점을 맞 춥니 다.
이는 다음과 같이 양식을 레이아웃 할 수 있음을 의미합니다.
<form>
<label for="login-validation-form-email">Email Address:</label>
<input type="text" class="login-validation-form-email" />
</form>
아아, 실제 코드 :
$(function(){
$('body').on('click', 'label', function(e){
var labelFor = $( this ).attr('for');
if( !document.getElementById(labelFor) ){
e.preventDefault(); e.stopPropagation();
var input = $( this ).siblings('.'+labelFor);
if( input )
input[0].focus();
}
})
});
참고 :이 <label>
for
속성은 페이지에서 ID가 일치하는 요소가 항상 있어야하기 때문에 W3C 사양에 따라 사이트를 확인할 때 문제가 발생할 수 있습니다 .
도움이 되었기를 바랍니다!
간단히 말해서, ID는 한 페이지에서 한 번만 사용되어야하므로 존재하지 않아야하는 단일 페이지에있는 여러 ID에 대한 해결 방법을 디자인하지 않습니다.
나머지 질문에 답하려면 : 아니요, ID 속성은 레이블의 'for'속성이 보는 유일한 것입니다. 항상 JavaScript onclick 이벤트를 사용하여 이름으로 입력을 가져 와서 변경할 수 있지만 ID 문제를 해결할 수있을 때는 지나치게 복잡해 보이므로 훨씬 더 의미가 있습니다.
아마도 쉬운 간단한 해결책은 uniqueid () php 또는 다른 프로그래밍 언어 대체 함수를 사용하는 것입니다.
'ProgramingTip' 카테고리의 다른 글
reCAPTCHA 오류 : 사이트 키에 대한 잘못된 도메인 (0) | 2020.11.23 |
---|---|
자바 펼쳐 함수에서 'undefined'또는 'null'을 반환하는 것이 더 낫습니까? (0) | 2020.11.23 |
테이블 셀의 링크를 전체 행 높이 채우기 (0) | 2020.11.23 |
Parallel.ForEach는 대형 개체가있는 열거 형으로 작업하는 경우 "메모리 부족"예외를 유발할 수 있습니다. (0) | 2020.11.23 |
asp.net mvc보기 모델의 언어 (0) | 2020.11.23 |