2013-03-26 4 views
5

DOM要素の特定の属性が定義されていないかどうか確認したいのですが、どうすればいいですか?要素が未定義であるかどうかを確認するにはどうすればよいですか?

私はこのような何か試してみました:あなたが見ることができるように、それは標準を生産しているので、参照エラーが変数が定義されていないことを私に語っているが、私のifチェックが明確に動作していない

if (marcamillion == undefined) { 
    console.log("Marcamillion is an undefined variable."); 
} 
ReferenceError: marcamillion is not defined 

をjs ReferenceError私が探しているエラーメッセージではなく、console.logです。

編集1まだ

以上、私は要素の属性は、次のように定義されていないかどうかを判断しようとしている場合:決定するための最良の方法だろう何

$(this).attr('value')

それが未定義ならば? typeofを使用して

+1

[変数が '未定義'か 'null'かを判断する方法](http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or- null)とhttp://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – lifetimes

答えて

8

:2番目の質問について

if (typeof marcamillion == 'undefined') { 
    console.log("Marcamillion is an undefined variable."); 
} 

編集:代わりに=====を使用して、より良いスタイルと見なされていること

if ($(this).attr('value')) { 
    // code 
} 
else { 
    console.log('nope.') 
} 
+0

私が値をテストしようとしている属性を持っているとします。つまり、 '$(this) .attr( 'value') '...それが未定義であるかどうかを判断する最良の方法は何でしょうか? – marcamillion

+1

'if($(this).attr( 'value'))'を実行するだけで動作します。 – romainberger

+0

パーフェクト。ありがとう! – marcamillion

4
if (typeof marcamillion === 'undefined') { 
    console.log("Marcamillion is an undefined variable."); 
} 

注意。

+0

「$(this).attr( 'value') '...の値をテストしようとしている属性があるとします。それが未定義であるかどうかを判断する最良の方法は何でしょうか? – marcamillion

関連する問題