Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - Add two variables using jquery

var a = 1;
var b = 2;
var c = a+b;

c will show as 12; but I need 3

How do I do it using jQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Definitely use jQuery

Because the power of jQuery is obviously unparalleled, here is how to do with with 100% jQuery:

var a = 1;
var b = 2;
$("<script>c=+("+a+")+ +("+b+")</script>").appendTo($(document));

Now c will hold your result and you used nothing but jQuery! As you can see jQuery is really great because it does all sorts of things

This also works well because it doesn't matter if a or b are strings!


Not enough jQuery?

var a = 1;
var b = 2;
$("<script id='test'>$('<textarea id=\'abc\'>'+("+a+")+ +("+b+")+'</textarea>').appendTo($('body'))</script>").appendTo('body');
var c = $("#abc").val();

This answer was done with 100% jQuery because jQuery is awesome but only use this carefully because it might not work sometimes.


jQuery Arithmetic Plugin

You can also use the revolutionary jQuery Arithmetic Plugin this has solved world peace in over 4294967295 (>> 0 === -1) countries:

var a = 1;
var b = 2;
var c = $.add(a,b);

while this is all great (this is not confirmed), but in jQuery -3.0.1 I have heard you will be able to add numbers this way:

$.number($.one, $.two).add($.number($.three, $.four))

this adds 12 (one + two) to 34 (three + four)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...