2017-02-07 4 views
1

のonclickイベントでその変数を呼び出すしたいと思い、私は出力を得る私は、関数で変数を宣言していると私は

var config = function() { 
    this.page.url = "http://localhost/test/echowrite_code.html"; 
    this.page.identifier = "this is the first post"; 
}; 

//i would like to get the config variable values in on click function 
$('#sendComment').on('click', function(){ 
console.log("url:"+config.page.url); 
    console.log("identifier :"+config.page.identifier); 
}); 

以下のような機能を持つ変数を宣言している:

url:undefined 
identifier:undefined 

が、予想される出力は次のようになります。

url:http://localhost/test/echowrite_code.html 
identifier: this is the first post 

しかし、私は

を期待していどのような値を取得しておりません
+0

で、その後

var config = function() { var page={ url : "http://localhost/test/echowrite_code.html"; identifier : "this is the first post"; } return page; }; 

私はあなたが取得しているどのような値1をexpecting_ていますどのような値を得ていないのです_but? 2.あなたはどのような価値を期待していますか? –

+0

なぜ 'config'が機能していますか? – Andreas

+1

「this.page」とは何でしょうか?関数で 'this'を使用したいのであれば、通常はオブジェクトまたはプロトタイプでなければなりません。 – Barmar

答えて

0

あなたが関数からオブジェクトを返すと、uはそれをしたい場合は、それを使用することができ、オブジェクト

var config = { 
 
    page : { 
 
     url : "http://localhost/test/echowrite_code.html", 
 
     identifier : "this is the first post" 
 
    } 
 
}; 
 

 
//i would like to get the config values in on click function 
 
$('#sendComment').on('click', function(){ 
 
console.log(config.page.url); 
 
    console.log(config.page.identifier); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="sendComment">Click</button>

+3

これは単なるオブジェクトであり、JSONとは関係ありません。 – Barmar

+2

[「JSONオブジェクト」のようなものはありません](http://benalman.com/news/2010/03/theres-no-suchthing-as-a-json/) – Andreas

+0

okオブジェクトのみ、編集 –

0

を作成する必要があります。コード

$('#sendComment').on('click', function(){ 
console.log(config().url); 
    console.log(config().identifier); 
}); 
関連する問題