簡體   English   中英

如何在同一個類,id和名稱中的字段中獲取最高價值的文本?

[英]How to get highest value text while field in same class, id and name?

我想從同一類的文本字段中最高的值中獲取價值,我試圖制作這樣的腳本,但它不起作用。

<input class="resbobot" name="BobotY2" id="BobotY2" type="text"value="100">
<input class="resbobot" name="BobotY3" id="BobotY3" type="text"value="80">
<input class="resbobot" name="BobotY4" id="BobotY4" type="text"value="70">

JS

$(".resbobot").each(function() {
   if ($(this).val()===100) { 
       alert($(this).val()); 
   }

===運算符比較值和類型。 您的代碼正在將字符串文字'100'與數字100進行比較。您可以使用==運算符忽略類型,或按照@RGS建議使用parseInt(..)

var max = 0
$(".resbobot").each(function() { if ($(this).val()>max) { max = $(this).val()}) 
alert(max)
$(".resbobot").each(function() {
 if(parseInt($(this).val())===100)
 {
  alert($(this).val());
 }
});

您必須使用字符串數據類型(即'')檢查文本框值,否則必須使用整數數據類型檢查文本框值,因為您使用的是相等值和相等類型運算符。

演示:

http://jsfiddle.net/h9jap3gp/1/

===檢查類型和值,==檢查值。 因此,“ 100” === 100返回false,而“ 100” == 100返回true。

要使用jQuery從輸入字段中找到最大值,請使用以下代碼:

var highestVal = null;
$('.resbobot').each(function(){
    var curVal = Number($(this).val());
    highestVal = (highestVal === null || highestVal < curVal) ?  curVal : highestVal;        
});   

alert(highestVal);

即使輸入值均為負數,上述代碼也將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM