简体   繁体   English

this.id对应于变量

[英]this.id corresponds to variable

I have a list of variables that correspond to numbers. 我有一个与数字相对应的变量列表。 I use these variables to write numbers to a "screen" in a web app I'm building for fun. 我使用这些变量将数字写到正在构建的Web应用程序的“屏幕”中。

var zero = 0;
var one = 1;
var two = 2;
var three = 3;
var four = 4;
var five = 5;
var six = 6;
var seven = 7;
var eight = 8;
var nine = 9;
var dec = ".";
var neg = "-";

示例图片

I used to have a long list of onclick functions for each of the buttons: 过去,每个按钮都有一长串的onclick函数:

$('#a0').click(function(){
    writeInput(input, zero);
});

$('#a1').click(function(){
    writeInput(input, one);
});
$('#a2').click(function(){
    writeInput(input, two);
});
...

I want to convert all of these click functions into something like this: 我想将所有这些单击函数转换为如下形式:

$('.btnA').click(function(){
    var id = this.id;
    writeInput(input, id);
});

Which calls this function: 哪个调用此函数:

function writeInput(field, str){
var text = $(field).val(function(i, v){
              return v + str;
           }).text(function(i, t){
              return t + str
           }).val();
convert(text, version);

} }

All of the buttons on the number input above have this HTML: 上面输入的数字上的所有按钮都具有以下HTML:

...
<a id="seven" class="btnA"><div class="inputBtn mar" id="input7">7</div></a>
<a id="eight" class="btnA"><div class="inputBtn mar" id="input8">8</div></a>
<a id="nine" class="btnA"><div class="inputBtn" id="input9">9</div></a>
...

My question is: Can I get the id name from the <a id="nine" class="btnA"> and have it correspond to the var nine = 9; 我的问题是:我可以从<a id="nine" class="btnA">获取ID名称,并使其与var nine = 9;对应<a id="nine" class="btnA"> var nine = 9;

I hope this made sense. 我希望这是有道理的。 If not please ask I will answer any questions. 如果没有,请询​​问我将回答任何问题。 Thanks! 谢谢!

Use an object with the ID's as keys, and you'll get numbers back: 使用带有ID的对象作为键,您将获得数字:

var numbers = {one: 1, two: 2, three: 3, .....};

$('.btnA').click(function(){
    var id = numbers[this.id];
    writeInput(input, id);
});

You can use data-type attribute and write something that: 您可以使用数据类型属性并编写以下内容:

<a data-number="7" class="btnA"><div class="inputBtn mar" id="input7">7</div></a>

$('.btnA').click(function(){
    var number = $(this).data('number');
    writeInput(input, number);
});

This should do it: 应该这样做:

$('.btnA').click(function() {
    var t = $(this).text(),
        n = parseInt(t, 10);
    writeInput(input, isNaN(n) ? t : n);
});

However, you could as well extract the number from the id attribute (just substr the "a") or even better use data attributes for them instead of reading the button text. 但是,你还可提取id属性的数量(只substr的“A”)或为他们更好地利用数据属性的读取按钮文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM