【问题标题】:How to implement a plus/minus button in a calculator work?如何在计算器工作中实现加号/减号按钮?
【发布时间】:2016-06-01 08:34:24
【问题描述】:

我想在计算器上创建一个按钮,可以将正数转换为负数,也可以将负数转换为正数。

这是js中的代码:

function reverse_num(){
    var num = $( "#p").text();
    if(num > 0){
        $("p").prepend("-");
    }
    else if(num = 0)
    {
        $("p");
    }
}

当我想将正面转换为负面时,它可以正常工作。但是当我想删除那个负号时,我不知道该怎么做。

谁能教我怎么做?

【问题讨论】:

  • else if(num = 0) 将 0 分配给 num。你想要else if(num == 0)else if(num === 0)

标签: javascript jquery calculator


【解决方案1】:

您应该使用基本数学并在单击减号时乘以 -1。

例如:

//Get the number
var number = parseFloat( $( "#p").text() );

//Reverse it
function reverse_num(num) {
    return (-num); // == (-1 * num)
}

//Replace the content of #p
$("#p").text( reverse_num(number) );

作为“单行者”

$("#p").text(-(parseFloat($("#p").text())));

【讨论】:

  • 或者在数字前加上“-”就足够了:number = -number
  • 确实,我想我是想展示流程……但还是更新了。
  • 感谢您的建议~我可以使用JQery方法text()来获取原始数字并将其反转,但是如何将这个数字设置为p的内容?
【解决方案2】:

你可以通过两种方式使用它

Way 1:您可以使用replace('-', '')删除"-"

Way 2 :您也可以通过(-1) 使用multiplication

function reverse_num(){
    var num = $( "#p").text();
	if(num > 0){    
       $("p").prepend("-");
	}
	else if(num < 0){
        var num = $( "#p").text().replace('-', '');
		$("#p").text(num);
	}
	else if(num == 0){
	   $("#p");
	} 
}

reverse_num();

function reverse_num_version_2(){
    var num = $( "#number").text();
	if(num > 0){    
       $("#number").prepend("-");
	}
	else if(num < 0){
        num = num * (-1);
		$("#number").text(num);
	}
	else if(num == 0){
	   $("#number");
	} 
}
reverse_num_version_2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p id="p">-100</p>

<div id="number">-100</div>

【讨论】:

  • 这是完成任务的一种非常糟糕的方式。你的代码做了很多额外的工作。 .replace()是字符串函数,OP正在构建计算器...
  • 可能不是最好的方法,但我想帮助@Vinny Mannello
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2019-01-25
  • 2017-01-02
  • 2016-04-20
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多