3

我可能忽略了一种更明显的方式来做我想做的事,但是......

我有一个 JS 变量列表,其名称与我页面上某些元素的 ID 相同。当我单击其中一个元素时,我希望能够使用单击的元素的 ID 来确定应该在我的函数中使用哪个变量。我的变量名称对应于我的元素 ID - 必须有某种方法来获取我单击的元素 ID 的值,$(this).id然后找到与该字符串匹配的变量?需要明确的是,变量的内容与变量名称或元素 ID 完全无关 - 变量是在页面加载时设置的,我想避免在每次运行函数时设置它们!而且我知道我可能会使用onclick它,但我试图避免这种情况,因为显然它现在很差?!

谢谢!

4

4 回答 4

2

I recommend you to make an array with al of your ids names

thisArray = {
    uniqueID1: 'Your value for uniqueID1',
    uniqueID2: 'Your value for uniqueID2'
};

you can call an element by a class for example

HTML:

<div id="uniqueID1" class="elements_class"> Div Content </div>
<div id="uniqueID2" class="elements_class"> Div Content </div>

jQuery:

$('div.elements_class').click(function(){
    var now_id = $(this).attr('id');
    alert(thisArray[now_id]);
});
于 2013-04-30T01:33:53.790 回答
1

看起来你想要的是使用.data()

$(el).data('myobject', {
    x: 123,
    y: 456
});

然后检索:

$(el).on('click', function() {
    var obj = $(this).data('myobject');
});
于 2013-04-30T01:35:13.847 回答
0

If you use an object to store the variables you are talking about with key/value pairings, you can just call variableObject[this.id] to get that variable.

于 2013-04-30T01:30:28.647 回答
0

Did you think of storing them in an object?

Example :

var obj = {
   'id1' : value1,
   'id2' : value 2,
   //...
}

Then you can acces them like that

obj[this.id]
于 2013-04-30T01:31:36.957 回答