簡體   English   中英

如何在通常的JS函數中訪問JQuery屬性

[英]How do I access JQuery property inside a usual JS 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).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);
  });

}

在上面的例子中,我得到一個異常,因為存儲在數組中的值只是純HTML代碼。

不,他們是jQuery實例。 在jQuery實例上調用Number.parseFloat將返回NaN *。

如果要訪問文本,則不需要執行任何特殊操作,條目是jQuery對象,只需直接調用.text()

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

*(因為parseFloat會將對象強制轉換為字符串,獲取"[object Object]" ,並且"[object Object]"無法解析為float)


在看到完整的功能,如你所說的評論,你要使用.texta為好。 這是和其他一些說明:

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> 

似乎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);
    });
}

運行示例:

 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); 
 <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> 

在那里,我使用了你的arr.forEach -assign-to- arr[index]模式而不是你想要的map (它確實避免了創建兩個不必要的數組)。

暫無
暫無

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

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