【问题标题】:How to check if the value in a text box is prime or not with jQuery如何使用jQuery检查文本框中的值是否为素数
【发布时间】:2014-07-28 11:38:56
【问题描述】:

我正在尝试使用 jQuery 确定文本框中的值是否为素数。

这是我迄今为止尝试过的,但它不起作用:

$("#textbx").keyup(function(){
 if ($("#textbx").val().length > 0) {
	  $("#btn").removeAttr('disabled');
 
   }
});

 $("#textbx").blur(function(){
    if ($("#textbx").val().length ==0) {
	  $("#btn").attr('disabled','disabled');
 
   }
  });
 
 $("#textbx").keypress(function (e) {
     if (e.which!=8 && (e.which < 48 || e.which > 57)) {
        $("#msg").html("plz press nimber only").show().fadeOut("slow");
               return false;
    }
   });
 
  $("#btn").click(function(){
						  
   var num =parseInt($("#textbx").val()); 
   var i;

   for (var i = 2; i >num/2; i++) { 
   
        if(i%num==0)
		{ $("#msg").html("yupp").show().fadeOut("slow");
		}
		else
		{$("#msg").html("huh").show().fadeOut("slow");
		}
		break;
       }
  });
#msg
{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>
 <span id="msg"></span>

JSFiddle 版本:http://jsfiddle.net/akash4pj/72FtQ/

【问题讨论】:

标签: javascript jquery primes


【解决方案1】:

这里是您的代码稍作修改

演示http://jsfiddle.net/72FtQ/1/

function isPrime(n) {

   // If n is less than 2 or not an integer then by definition cannot be prime.
   if (n < 2) {return false}
   if (n != Math.round(n)) {return false}

   // Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
   for (var i = 2; i <= Math.sqrt(n); i++) {
      if (n % i == 0) {return false}
   }

   // If n%i was never == 0 above, then n must be prime
   return true;

}

来源http://studymaths.co.uk/topics/checkIfPrime.php

【讨论】:

  • 但是你能告诉我我的代码有什么问题吗?为什么它不能工作?
  • 不错。将Math.sqrt(n) 缓存在一个变量中并使用它来绑定for 循环可能会带来较小的性能改进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 2020-05-29
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 2018-10-23
相关资源
最近更新 更多