2013-04-21 37 views
0

这是准确报告console.log中文本字段的长度,但它也会在每个keyup上的代码下面抛出错误。有什么想法吗?JavaScript长度函数在文本字段上抛出错误

$('.search').keyup(function() { 
    var searchTerm = this.value; 
      console.log(this.value.length); 
      if (this.value.length>0){ 
      getSuggestions(searchTerm); 
      }else{ 
       $('#Button').click(); 
      } 
     }) 

而这就是我得到了Chrome的控制台

Uncaught TypeError: Cannot read property 'length' of undefined pm_functions.js:283 
(anonymous function) pm_functions.js:283 
p.event.dispatch jquery.min.js:2 
g.handle.h 
+2

什么是元素(S)与类“搜索”的HTML我解决?你能够确定(在Chrome脚本调试器视图中)确定这是导致问题的代码行吗?如果'console.log()'起作用,后续行会引发异常似乎很奇怪。 – Pointy 2013-04-21 14:42:23

+2

你可能的意思是'$(this)'不'这个' – 2013-04-21 14:44:41

+0

尝试$(this).val()和/或$(this).text()而不是this.value – 2013-04-21 14:45:12

回答

1

好吧,解决了。谢谢您的帮助。我注意到keyup发射两次。错误正在被抛出第二次。当我仔细查看HTML时,我发现父母也在使用“.search”类。

因此,这里是使用强ID输入字段

$('#searchInputField').keyup(function() { 
      var searchTerm = this.value; 
      if (searchTerm.length > 2){ 
      getSuggestions(searchTerm); 
      }else{ 
       $('#Button').click(); 
      } 
     }) 
2

尝试$(this).val().length

+0

是的,我也试过jquery。同样的结果。 – frankie 2013-04-21 14:49:35

+0

为什么?这导致尝试访问未定义的'length'属性 - 这些语句绝对是等价的(对于大多数输入类型) – Bergi 2013-04-21 15:01:44

0

更换this.value.length您可以测试的THIS.VALUE值:

$('.search').keyup(function() { 
var searchTerm = this.value; 
     console.log(this.value.length); 
     if ((this.value.length>0) && (searchTerm !== null)){ 
      getSuggestions(searchTerm); 
     } 
     else { 
      $('#Button').click(); 
     } 
    }) 
1

这是一个盲目的答案,因为你必须分享你的html

$('.search').keyup(function() { 
    var searchTerm = $(this).val(); 
    if (searchTerm && searchTerm.length>0){ 
     getSuggestions(searchTerm); 
    }else{ 
     $('#Button').click(); 
    } 
})