简体   繁体   中英

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.

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:

$('#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:

...
<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;

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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