2012-09-28 47 views
1

我不是一個JavaScript開發人員,但我堅持JS問題。Javascript更新導致悲傷

如果有人能幫我弄清楚問題可能會是驚人的。

腳本的位被倒下的是:

 $('button').each(function() 
      { 
      var curr_title = $(this).attr('title'); 

      if(curr_title.length > 0) $(this).button({ icons: { primary: curr_title } }); 
      else      $(this).button(); 
      }); 

的錯誤是

TypeError: Cannot read property 'length' of undefined.

這工作沒有任何問題,在所有的代碼以前的版本。但唯一的變化是更新Jquery。

有誰知道這可能是問題嗎?

再次。道歉,如果我是愚蠢的。

回答

0

$(this).attr('title');是未定義的,所以沒有長度。沒有您的按鈕包含一個標題,如果你的羯羊的attibute存在測試嘗試:

$('button').each(function() 
      { 
      var curr_title = $(this).attr('title'); 

      if(curr_title != undefined) 
       $(this).button({ icons: { primary: curr_title } }); 
      else       
       $(this).button(); 
      }); 
0

看起來你可能在沒有「標題」屬性的標記中有一個按鈕。對於這個按鈕(或多個按鈕)curr_title未定義,所以調用.length就會產生異常

+0

所以用不確定的答案抵禦這個錯誤,並檢查您的標記 –

2

在此行中返回的值是undefined(大概是因爲按鈕,它是指已指定要沒有這樣的屬性。)

var curr_title = $(this).attr('title'); 

jQuery的版本改變attr()行爲1.6

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.

所以在if stateme通話nt失敗。 「包修」這個,你可以只添加一個檢查爲undefined這樣的:

if((typeof curr_title != 'undefined') && (curr_title.length > 0)) { 
    $(this).button({ icons: { primary: curr_title } }); 
} else { 
    $(this).button(); 
} 
+0

不確定的不應該是一個字符串。這是一個對象。 – Liam

+2

@liam我在哪裏指定'undefined'作爲字符串?如果你的意思是'typeof ...'語句,那麼看看這個規範,因爲['typeof'總是返回一個字符串](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/運營商/ typeof運算)! – Sirko

+0

夠公平的,沒有看到什麼優勢類型帶來這個作爲一個單獨的說明,但你去 – Liam