我用函数声明了变量,我想在onc​​lick事件中调用该变量

时间:2017-02-07 11:46:01

标签: jquery 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

但我没有得到我期待的价值

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);
 });