如何从锚标记中获取值并将其用于其他函数

时间:2016-01-13 05:39:40

标签: javascript jquery

我有一个非常简单的问题,但我无法弄清楚, 对此我是新手。

我有以下功能,用户将点击他/她想要搜索的内容的按钮,然后当他/她选择并点击选项周围的内容时,他/她将点击搜索按钮进行搜索。

这是我从锚标记中获取值的代码,选项包含在锚标记中。

$(document).on('click' , '#area_id_1' , function(){ 
var getText1 = $("#area_id_1").text();
alert(getText1); return false; });



$(document).on('click' , '#area_id_2' , function(){ 
var getText1 = $("#area_id_2").text();
alert(getText1);
return false; 
});



$(document).on('click' , '#area_id_3' , function(){ 
var getText1 = $("#area_id_3").text();
alert(getText1); return false;});



$(document).on('click' , '#area_id_4' , function(){ 
var getText1 = $("#area_id_4").text();
alert(getText1);
return false;
});



$(document).on('click' , '#area_id_5' , function(){ 
var getText1 = $("#area_id_5").text();
alert(getText1); return false;});



$(document).on('click' , '#area_id_6' , function(){ 
var getText1 = $("#area_id_6").text();
alert(getText1); return false;  });



$(document).on('click' , '#area_id_7' , function(){ 
var getText1 = $("#area_id_7").text();
alert(getText1); return false;  });


$(document).on('click' , '#area_id_8' , function(){ 
var getText1 = $("#area_id_8").text();
alert(getText1); return false; });

这是我的搜索按钮功能 //搜索功能按钮

$(document).on('click', '#btnSearch', function() {

}

问题是,我如何能够存储我从锚标签获得的值,以便在单击btnSearch函数时可以使用它?

3 个答案:

答案 0 :(得分:0)

首先定义你的变量getText1 global ,如下所示。

var getText1;

$(document).on('click' , '#area_id_1' , function(){ 
    getText1 = $(this).text();
    return false; 
});

...(rest of your code)
// and you will get the variable in below function

$(document).on('click', '#btnSearch', function() {
    alert(getText1); // you can check here if it is empty or not
}

答案 1 :(得分:0)

您需要使用全局变量或窗口变量..请参阅此 Click ..我会提一些例子

<script>
var yourGlobalVariable;   // this is global variable
function foo() {
    // ...
}
</script>


<script>
function foo() {
    window.yourGlobalVariable = ...;   // this is window variable you can use
}
</script>

答案 2 :(得分:0)

首先,我不建议使用全局变量。 Global variable is bad practice

如果您不想使用全局变量。 您可以在btnSearch元素上设置值。 使用jQuery.fn.data函数,可以将值存储到具有特定键字符串的元素。 https://api.jquery.com/data/

您可以使用多个选择器。将相同的事件处理函数附加到多个元素一次。 https://api.jquery.com/multiple-selector/

// You can use same handler function on multiple element once.
// You don't have to declare same function each time.
$('#area_id_1, #area_id_2, #area_id_3, #area_id_4' +
', #area_id_5, #area_id_6, #area_id_7, #area_id_8').on('click', function() {
    var text = $(this).text();
    // Set value at $('#btnSearch') with "text" key
    $('#btnSearch').data("text", text);
    alert(text);
    return false;
});

$(document).on('click', '#btnSearch', function() {
    var text = $(this).data("text"); // You can get the value like this
}
相关问题