如何在通常的JS函数中访问JQuery属性

时间:2018-02-02 07:32:14

标签: javascript jquery arrays function

我有一个函数,它将一个数组作为参数,然后处理它并更改该数组的值。问题是数组是由JQuery节点(通常的span)组成的,我通过调用.text() JQuery方法来访问这个span值。这是它的外观:

var array= 
[
    $('*[id$=id1]'),
    $('*[id$=id2]'),
    $('*[id$=id3]'),
    $('*[id$=id4]'),
    $('*[id$=id5]')
] // Ignore the weird way of the selectors. It's just a feature of back-end technology I use

function removeZeros(arr) 
{
  var map = arr.map(function(a) {
   //logic to perform...
  }
  arr.forEach(function(value, index, arr) 
  {
  arr[index] = Number.parseFloat(value).toFixed(maxNum);
  });
  //Rewriting the values..
  }
}

removeZeros(array)

在上面的示例中,我得到一个异常,因为存储在数组中的值只是纯HTML代码。我之前提到过使用.text()访问的真正价值。所以我需要在函数调用此方法中使 a 。 我试过(函数($(a).text()(函数($(a.text())(函数($ a) .text())到目前为止,但似乎没有任何效果,它会引发一个令人讨厌的例外情况。无论如何我如何访问text()

整个功能:

function removeZeros(arr) 
{
  var map = arr.map(function(a)
  {
  if (a % 1 === 0) 
  {
  var res = "1";
  } 
  else 
  {
      var lastNumman = a.toString().split('').pop();
      if (lastNumman == 0)
      {
        var m = parseFloat(a);
        var res = (m + "").split(".")[1].length;
      } 
      else 
      {
        var m = a.split(".")[1].length;
        var res = m;
      }
  }
  return res;

  });

  var maxNum = map.reduce(function(a, b) {
    return Math.max(a, b);
  });

  arr.forEach(function(value, index, arr) {
  arr[index] = Number.parseFloat(value.text()).toFixed(maxNum);
  });

}

1 个答案:

答案 0 :(得分:3)

  

在上面的示例中,我得到一个异常,因为存储在数组中的值只是纯HTML代码。

不,他们是jQuery实例。在jQuery实例上调用Number.parseFloat将返回NaN *。

如果你想访问文本,你不需要做任何特别的事情,条目是一个jQuery对象,只需直接在其上调用.text()

arr[index] = Number.parseFloat(value.text()).toFixed(maxNum);
// ---------------------------------^^^^^^^

*(因为parseFloat会将对象强制转换为字符串,获取"[object Object]"并且"[object Object]"无法解析为浮点数)

正如您在评论中所说,看过完整功能后,您也希望在.text上使用a。以下是其他注意事项:

function removeZeros(arr) {
    var map = arr.map(function(a) {
        var res, astNumman, m;

        // *** Get the text of the entry
        a = a.text();

        if (a % 1 === 0) { // *** ? `a` is a string. This will coerce it to number and then do % on it.
            res = "1";
        } else {
            lastNumman = a[a.length-1];              // *** Much more efficient than `a.split('').pop();`
            if (lastNumman == 0) {                   // *** Again using a string as a number
                m = parseFloat(a);
                res = (m + "").split(".")[1].length; // *** The *length* of the fractional portion?
            } else {
                m = a.split(".")[1].length;
                res = m;
            }
        }
        return res;
    });

    var maxNum = map.reduce(function(a, b) {
        return Math.max(a, b);
    });

    // ***
    arr.forEach(function(value, index, arr) {
        arr[index] = Number.parseFloat(value.text()).toFixed(maxNum);
    });
}

运行示例:



var array= 
[
    $('*[id$=id1]'),
    $('*[id$=id2]'),
    $('*[id$=id3]'),
    $('*[id$=id4]'),
    $('*[id$=id5]')
];

function removeZeros(arr) {
    var map = arr.map(function(a) {
        var res, astNumman, m;

        // *** Get the text of the entry
        a = a.text();

        if (a % 1 === 0) { // *** ? `a` is a string. This will coerce it to number and then do % on it.
            res = "1";
        } else {
            lastNumman = a[a.length-1];              // *** Much more efficient than `a.split('').pop();`
            if (lastNumman == 0) {                   // *** Again using a string as a number
                m = parseFloat(a);
                res = (m + "").split(".")[1].length; // *** The *length* of the fractional portion?
            } else {
                m = a.split(".")[1].length;
                res = m;
            }
        }
        return res;
    });

    var maxNum = map.reduce(function(a, b) {
        return Math.max(a, b);
    });

    // ***
    arr.forEach(function(value, index, arr) {
        arr[index] = Number.parseFloat(value.text()).toFixed(maxNum);
    });
}

removeZeros(array);
console.log(array);

<div id="id1">7</div>
<div id="id2">6.4324</div>
<div id="id3">8.24</div>
<div id="id4">8998.3</div>
<div id="id5">0</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

似乎removeZeroes的目标是将jQuery对象数组转换为字符串数组,其中对象的文本转换为数字,然后转换为字符串,其中所有数字后面的数字都相同小数(最长的)。如果是这样,我们可以更有效率:

function removeZeros(arr) {
    // Find longest decimal portion, convert jQuery objects to numbers
    var longest = -Infinity;
    arr.forEach(function(entry, index) {
        var num = parseFloat(entry.text());
        var str = String(num);
        var decimal = str.indexOf(".");
        var thisLength;
        if (decimal === -1) {
            thisLength = 1;
        } else {
            thisLength = str.length - decimal - 1;
        }
        if (thisLength > longest) {
            longest = thisLength;
        }
        arr[index] = num;
    });

    // Format numbers as strings
    arr.forEach(function(num, index) {
        arr[index] = num.toFixed(longest);
    });
}

运行示例:

&#13;
&#13;
var array= 
[
    $('*[id$=id1]'),
    $('*[id$=id2]'),
    $('*[id$=id3]'),
    $('*[id$=id4]'),
    $('*[id$=id5]')
];

function removeZeros(arr) {
    // Find longest decimal portion, convert jQuery objects to numbers
    var longest = -Infinity;
    arr.forEach(function(entry, index) {
        var num = parseFloat(entry.text());
        var str = String(num);
        var decimal = str.indexOf(".");
        var thisLength;
        if (decimal === -1) {
            thisLength = 1;
        } else {
            thisLength = str.length - decimal - 1;
        }
        if (thisLength > longest) {
            longest = thisLength;
        }
        arr[index] = num;
    });

    // Format numbers as strings
    arr.forEach(function(num, index) {
        arr[index] = num.toFixed(longest);
    });
}

removeZeros(array);
console.log(array);
&#13;
<div id="id1">7</div>
<div id="id2">6.4324</div>
<div id="id3">8.24</div>
<div id="id4">8998.3</div>
<div id="id5">0</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我已经使用了您的arr.forEach - 分配到 - arr[index]模式而不是map,因为您似乎更喜欢它(它确实避免创建两个不必要的数组)