program tip

“class”및“id”HTML 속성 이름 지정-대시와 밑줄

radiobox 2020. 8. 5. 08:05
반응형

“class”및“id”HTML 속성 이름 지정-대시와 밑줄


<div id="example-value">또는 <div id="example_value">?

이 사이트와 트위터는 첫 번째 스타일을 사용합니다. 페이스 북과 비 메오 – 두 번째.

어느 것을 사용하고 왜?


하이픈을 사용하여 HTML과 JavaScript를 분리하십시오.

왜? 아래를 참조하십시오.

하이픈은 CSS 및 HTML에서 유효하지만 JavaScript 객체에는 사용할 수 없습니다.

많은 브라우저가 큰 프로젝트에서 창 / 문서 객체에 HTML Id를 전역 객체로 등록하면 큰 고통이 될 수 있습니다.

이러한 이유로 HTML ID가 내 JavaScript와 충돌하지 않도록 하이픈으로 이름을 사용합니다.

다음을 고려하세요:

message.js

message = function(containerObject){
    this.htmlObject = containerObject;
};
message.prototype.write = function(text){
    this.htmlObject.innerHTML+=text;
};

html

<body>
    <span id='message'></span>
</body>
<script>
    var objectContainer = {};
    if(typeof message == 'undefined'){
        var asyncScript = document.createElement('script');
        asyncScript.onload = function(){
            objectContainer.messageClass = new message(document.getElementById('message'));
            objectContainer.messageClass.write('loaded');
        }
        asyncScript.src = 'message.js';
        document.appendChild(asyncScript);
    }else{
        objectContainer.messageClass = new message(document.getElementById('message'));
        objectContainer.messageClass.write('loaded');
    }
</script>

브라우저가 HTML ID를 전역 객체로 등록하면 메시지가 '정의되지 않은'것이 아니기 때문에 위의 작업이 실패하고 HTML 객체의 인스턴스를 만들려고 시도합니다. HTML ID에 이름에 하이픈이 있는지 확인하면 아래와 같은 충돌을 방지 할 수 있습니다.

message.js

message = function(containerObject){
    this.htmlObject = containerObject;
};
message.prototype.write = function(text){
    this.htmlObject.innerHTML+=text;
};

html

<body>
    <span id='message-text'></span>
</body>
<script>
    var objectContainer = {};
    if(typeof message == 'undefined'){
        var asyncScript = document.createElement('script');
        asyncScript.onload = function(){
            objectContainer.messageClass = new message(document.getElementById('message-text'));
            objectContainer.messageClass.write('loaded');
        }
        asyncScript.src = 'message.js';
        document.appendChild(asyncScript);
    }else{
        objectContainer.messageClass = new message(document.getElementById('message-text'));
        objectContainer.messageClass.write('loaded');
    }
</script>

물론 messageText 또는 message_text를 사용할 수는 있지만 문제가 해결되지 않으며 나중에 JavaScript 객체 대신 HTML 객체에 실수로 액세스하는 동일한 문제가 발생할 수 있습니다.

한 가지 설명은 window [ 'message-text']를 사용하여 (예를 들어) window 객체를 통해 HTML 객체에 계속 액세스 할 수 있다는 것입니다.


Google HTML / CSS 스타일 가이드를 추천합니다

그것은 구체적으로 말합니다 :

Separate words in ID and class names by a hyphen. Do not concatenate words and abbreviations in selectors by any characters (including none at all) other than hyphens, in order to improve understanding and scannability.

/* Not recommended: does not separate the words “demo” and “image” */
.demoimage {}

/* Not recommended: uses underscore instead of hyphen */
.error_status {}

/* Recommended */
#video-id {}
.ads-sample {}

It really comes down to preference, but what will sway you in a particular direction might be the editor you code with. For instance, the auto-complete feature of TextMate stops at a hyphen, but sees words separated by an underscore as a single word. So class names and ids with the_post work better than the-post when using its auto-complete feature (Esc).


I believe this is entirely up to the programmer. You could use camelCase too if you wanted (but I think that would look awkward.)

I personally prefer the hyphen, because it is quicker to type on my keyboard. So I would say that you should go with what you are most comfortable with, since both your examples are widely used.


Either example is perfectly valid, you can even throw into the mix ":" or "." as separators according to the w3c spec. I personally use "_" if it is a two word name just because of its similarity to space.


I use the first one (one-two) because its more readable. For images though I prefer the underscore (btn_more.png). Camel Case (oneTwo) is another option.


Actually some external frameworks (javascript, php) have difficulties (bugs?) with using the hypen in id names. I use underscore (so does 960grid) and all works great.


I would suggest underscore mainly for the reason of a javascript side-effect I'm encountering.

If you were to type the code below into your location bar, you would get an error: 'example-value' is undefined. If the div were named with underscores, it would work.

javascript:alert(example-value.currentStyle.hasLayout);

참고URL : https://stackoverflow.com/questions/1696864/naming-class-and-id-html-attributes-dashes-vs-underlines

반응형