2017-02-07 5 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

_but я не получаю значения, что я expecting_ 1. Какое значение вы получаете? 2. Какую ценность вы ожидаете? –

+0

Почему 'config' является функцией? – Andreas

+1

А что такое 'this.page'? Если вы хотите использовать 'this' в функции, это обычно должно быть в объекте или прототипе. – Barmar

ответ

0

вам нужно создать объект

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-such-thing-as-a-json/) – Andreas

+0

ok просто объект, отредактируйте –

0

вы можете вернуть объект из функции и использовать его, если и хотят.

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

затем в коде

$('#sendComment').on('click', function(){ 
console.log(config().url); 
    console.log(config().identifier); 
});