검색 폼에 빈 검색 검색을 방지해야합니다. 형태의 버튼을 제출이없는, 그래서 입력 방지해야javascript 두 개의 다른 요소에 대한 addEventListener 충돌
HTML 코드 :
형태 1
<form method="get" class="search-form" id="searchform" action="http://example.com" >
<input class="text" name="s" id="s" type="text" />
</form>
형태 2
<form action="http://example.com" class="search-form" method="get">
<input type="text" name="s" class="text">
</form>
자바 스크립트 코드
// Im sure this funcions returns the 2 different forms,
var searchForms = getElementsByClass('search-form');
for(i in searchForms)
{
if (searchForms[i].addEventListener)
{
searchForms[i].addEventListener("submit", function(e)
{
preventSubmit(e); // no problem here
console.log(i) // ALWAYS LOGS 1
});
} //I also implemented the ie code, but not necessary here, is the same as above for addEventListener
}
모든 양식을 제출할 때마다 콘솔에 1을 쓰고, 아이디어가 있습니까? 당신은 폐쇄 필요한 모든
너무 많은 중복 같은 [이것 (http://stackoverflow.com/questions/6487366/how-to-generate-event-handlers-with-loop-in-javascript). 부수적으로, 순차적 인 숫자 반복만을 원하면'for-in '을 사용하지 마십시오. 문제가 발생할 수 있습니다. –
preventSubmit (e); console.log (this) // 올바른 양식을 줄 것입니다. – SMathew
'i'는 요소가 아닌 색인에 대한 참조입니다. –