【问题标题】:JQuery - making variables with the $(this) selector global?JQuery - 使用 $(this) 选择器全局变量?
【发布时间】:2012-03-11 03:09:49
【问题描述】:

我有两个按钮,当单击它们时,它们都会调用不同的功能。两个函数共享相同的变量。我将如何使这些变量成为全局变量,以便它们可以由每个函数设置?示例:

$('#button_one').bind('click', functionOne);
$('#button_two').bind('click', functionTwo);

function functionOne(){
   var exOne = $(this).attr('id');
   var exTwo = $(this).text();

   // do stuff here
};

function functionTwo(){
   var exOne = $(this).attr('id');
   var exTwo = $(this).text();

   // do stuff here
};

如何实现这样的目标?

$('#button_one').bind('click', functionOne);
$('#button_two').bind('click', functionTwo);

exOne = $(this).attr('id');
exTwo = $(this).text();    

function functionOne(){
   // do stuff here
};

function functionTwo(){
   // do stuff here
};

感谢您的意见!!!

【问题讨论】:

  • 这些变量是不一样的——它们会为每个按钮包含不同的值。

标签: jquery variables css-selectors global


【解决方案1】:

将它们声明为全局 :)

$('#button_one').bind('click', functionOne);
$('#button_two').bind('click', functionTwo);

var exOne;
var exTwo;

function functionOne(){
   exOne = $(this).attr('id');
   exTwo = $(this).text();

   // do stuff here
};

function functionTwo(){
   exOne = $(this).attr('id');
   exTwo = $(this).text();

   // do stuff here
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 2021-03-30
    • 1970-01-01
    • 2010-09-19
    • 2011-11-08
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多