Development Tip

html 양식 태그의 목적은 무엇입니까

yourdevel 2020. 10. 27. 23:32
반응형

html 양식 태그의 목적은 무엇입니까


html에서 양식 태그의 목적을 이해하지 못합니다.

form 태그를 사용하지 않고 쉽게 모든 입력 유형을 완벽하게 사용할 수 있습니다. 입력을 감싸는 것은 거의 중복되어 보입니다.

또한 ajax를 사용하여 서버 측 페이지를 호출하는 경우 간단히 jQuery를 사용할 수 있습니다. 유일한 예외는 어떤 이유로 든 양식 태그를 업로드 스크립트로 감싸 야한다는 점입니다.

그렇다면 왜 양식은 텍스트 입력과 같은 단순한 일에 여전히 널리 사용됩니까? 그것은 매우 고풍스럽고 불필요한 일처럼 보입니다.

나는 그것에 대한 이점이나 필요를 보지 못합니다. 뭔가 빠졌 나봐요.


당신이 놓친 것은 시맨틱 마크 업과 DOM에 대한 이해입니다 .

현실적으로 HTML5 마크 업으로 원하는 모든 작업을 수행 할 수 있으며 대부분의 브라우저가이를 구문 분석합니다. 내가 마지막으로 확인했을 때 WebKit / Blink는 요소 내부의 의사 요소<input> 도 허용 합니다 . 이는 Gecko 사양을 위반하지 않습니다. 그러나 마크 업으로 원하는대로 수행하면 의미론에 관한 한 의심 할 여지없이 마크 업이 무효화됩니다.

<input>요소 안에 요소 를 넣는 이유는 무엇 <form>입니까? 같은 이유로 <li>태그를 <ul><ol>요소 내부에 넣습니다. 태그가 속한 곳입니다. 그것은의 의미 , 수정 및 마크 업을 정의하는 데 도움이됩니다. 구문 분석기, 화면 판독기 및 다양한 소프트웨어는 마크 업이 구조뿐 아니라 의미를 가질 때 의미 상 올 바르면 마크 업을 더 잘 이해할 수 있습니다.

<form>요소를 사용하면 양식이 제출 될 때 수행 할 작업을 브라우저에 알리는 methodaction속성 을 정의 할 수도 있습니다 . AJAX는 100 % 커버리지 도구가 아니며 웹 개발자로서 당신은 우아한 저하를 연습해야합니다. JS가 꺼져 있어도 양식을 제출하고 데이터를 전송할 수 있어야합니다.

마지막으로 양식은 모두 DOM에 올바르게 등록됩니다. JavaScript로이를 엿볼 수 있습니다. 바로이 페이지에서 콘솔을 열고 다음을 입력하면 :

document.forms

페이지에있는 모든 양식의 멋진 컬렉션을 얻을 수 있습니다. 검색 창, 주석 상자, 답변 상자-모든 적절한 양식. 이 인터페이스는 정보에 액세스하고 이러한 요소와 상호 작용하는 데 유용 할 수 있습니다. 예를 들어 양식은 매우 쉽게 직렬화 할 수 있습니다.

다음은 몇 가지 읽기 자료입니다.

참고 : <input>요소는 양식 외부에서 사용할 수 있지만 어떤 방식 으로든 데이터를 제출하려는 경우 양식을 사용해야합니다.


이것은 내가 질문을 뒤집는 대답의 일부입니다.

양식을 피함으로써 어떻게 내 삶을 더 힘들게 만들고 있습니까?

가장 중요한 것은 컨테이너 요소입니다. 누가 필요 하죠?!

확실히 당신의 작은 요소 <input><button>요소가 일종의 컨테이너 요소 안에 중첩 되어 있습니까? 그들은 다른 모든 것의 중간에 떠있을 수 없습니다. 그렇다면 <form>, 그렇다면 무엇입니까? A <div>? A <span>?

이러한 요소 어딘가에 있어야 하며 마크 업이 엉망이되지 않는 한 컨테이너 요소는 양식이 될 수 있습니다.

아니? 오.

이 시점에서 내 머릿속의 목소리는 이러한 모든 다양한 AJAX 상황에 대한 이벤트 핸들러를 만드는 방법에 대해 매우 궁금합니다. 바이트를 절약하기 위해 마크 업을 줄여야한다면 많은 것이 필요합니다. 그런 다음 요소의 각 '세트'에 해당하는 각 AJAX 이벤트에 대한 사용자 지정 함수를 만들어야합니다. 개별적으로 또는 클래스를 대상으로해야합니다. 맞습니까? 이러한 요소를 일반적으로 그룹화 할 수있는 방법은 없습니다. 우리는 마크 업 주변을 돌아 다니며 필요할 때까지 무엇이든 수행하도록 설정했기 때문입니다.

따라서 몇 가지 핸들러를 사용자 정의합니다.

$('#searchButton').on('click', function (e) {
  e.preventDefault();

  var search = $('#mySearch');

  $.ajax({
    url: 'http://example.com/text',
    type: 'GET',
    dataType: 'text',
    data: 'query=' + search.val(),
    success: function (data) {
      console.log(data);
    }
  });
});


$('#login').on('click', function (e) {
  e.preventDefault();
  var user = $('#username'),
      pass = $('#password'),
      rem = $('#remember');
  
  $.ajax({
    url: 'http://example.com/login',
    type: 'POST',
    data: user.add(pass, rem).serialize(),
    dataType: 'text',
    success: function (data) {
      console.log(data);
    }
  });
});
<!-- No containers, extra markup is silly. -->

<input type="text" id="mySearch" value="query" />
<button id="searchButton">Search</button>
<input type="text" id="username" name="username" value="user" />
<input type="password" id="password" name="password" value="pass" />
<input type="checkbox" id="remember" name="remember" checked /> stay logged in
<button id="login">Login</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

이것은 다음과 같이 말하는 부분입니다.

'하지만 재사용 가능한 기능을 완전히 사용합니다. 과장하지 마세요. '

Fair enough, but you still need to create these sets of unique elements, or target class sets, right? You still have to group these elements somehow.

Lend me your eyes (or ears, if you're using a screen reader and need some assistance - good thing we could add some ARIA to all this semantic markup, right?), and behold the power of the generic form.

function genericAjaxForm (e) {
  e.preventDefault();
  var form = $(this);
  
  return $.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    dataType: form.data('type'),
    data: form.serialize()
  });
}

$('#login-form').on('submit', function (e) {
  genericAjaxForm.call(this, e).done(function (data) {
    console.log(data);
  });
});
<form action="http://example.com/login" method="POST" data-type="text" id="login-form">
  <input type="text" name="username" value="user" />
  <input type="password" name="password" value="mypass" />
  <label>
    <input type="checkbox" name="remember" /> Remember me
  </label>

  <button type="submit">Login</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

We can use this with any common form, maintain our graceful degradation, and let the form completely describe how it should function. We can expand on this base functionality while keeping a generic style - more modular, less headaches. The JavaScript just worries about its own things, like hiding the appropriate elements, or handling any responses we get.

And now you say:

'But I wrap my pseudo-forms in <div> elements that have specific IDs - I can then target the inputs loosely with with .find, and .serialize them, and ...'

Oh, what's that? You actually wrap your <input> elements in a container?

So why isn't it a form yet?


Form tags are still necessary if you want to be able to submit the form without AJAX (which may be useful in the early stages of development). But even though it's possible to use javascript to submit data without a form tag, a few benefits still come to mind:

  1. Using form tags can help people read and understand you code in some cases, by showing them your intentions.
  2. The 'submit' method is available on forms. If you have a form with an input[type=submit], and it's not disabled, then when someone hits 'enter' while filling out one of the other form inputs, the form will submit. You can still do that by listening for the 'keydown' event on the input elements, but it's a nice bit of ui that you get for free with form tags.
  3. There are be a few other things that only work with a form tag, or are easier with a form tag. Developers will eventually run into these cases, and decide it's easier just to always use them everywhere and avoid problems. Really, the real question is, why not use a form tag?

The HTML element represents a document section that contains interactive controls to submit information to a web server.

We are all familiar with forms on html web pages. For many different reasons people or companies are asking for our e-mail addresses, names and site URLs. Buying products on the Internet today is mostly a breeze and with the advent of security devices, the method used for submitting your details and hard earned money is usually performed via forms.

more info

link one

link two

참고URL : https://stackoverflow.com/questions/31066693/what-is-the-purpose-of-the-html-form-tag

반응형