我必须防止在搜索表单上进行空搜索。 形式没有提交按钮,所以我必须要防止进入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>
javascript代码
// 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'。它可能会导致问题。 – 2012-07-06 18:07:46
preventSubmit(e); console.log(this)//会给你正确的形式 – SMathew 2012-07-06 18:07:08
'i'是对索引的引用,而不是元素。 – 2012-07-06 18:22:35