2017-05-19 90 views
-1

我有一個類是兩個名字,class = test-select r10,我得到了十行。例如:如何獲取該類包含2個名稱的getelementbyClassname?

var res = {}; 
 

 
var els; 
 
for (var r = 1; r <= 10; r++) { 
 
    els = document.getElementsByClassName("r" + r); 
 
    console.log("Found " + els.length + " for r" + r); 
 
    for (var i = 0; i < 4; i++) { 
 
    els[i].selectedIndex = res["r" + r][i]; 
 
    } 
 
}
<table> 
 
    <tr class="info" id="alertr1"> 
 
    <td width="30px">1</td> 
 
    <td width="200px">Likes Authority</td> 
 
    <td width="75px;"> 
 
     <select class="test-select r1" name="qtyL" onchange="this.size=1" onmouseout="this.size=1" onmouseover="this.size=this.options.length" style="position: absolute; z-index:9999;"> 
 
     <option value="0">-</option> 
 
     <option value="1">1</option> 
 
     <option value="2">2</option> 
 
     <option value="3">3</option> 
 
     <option value="4">4</option> 
 
     </select> 
 
    </td> 
 
    <td width="200px">Enthusiastic</td> 
 
    <td width="75px;"> 
 
     <select class="test-select r1" name="qtyO" onchange="this.size=1" onmouseout="this.size=1" onmouseover="this.size=this.options.length" style="position: absolute; z-index:9999;"> 
 
     <option value="0">-</option> 
 
     <option value="1">1</option> 
 
     <option value="2">2</option> 
 
     <option value="3">3</option> 
 
     <option value="4">4</option> 
 
     </select> 
 
    </td> 
 
    </tr> 
 
</table>

我如何使用getelementByClassName類的第二個名字?

+5

您沒有一類具有兩個名字,你有兩種不同類的元素。你是問如何選擇具有第二類的元素,或者如何找出給定第一類名的第二類的名稱?要麼...? – nnnnnn

+0

您可以將類名稱保存爲js變量並循環/選擇要使用的元素或子項。 – CodeMonkey

+0

您是否在問如何選擇具有第二類的元素 - 是的,這就是問題所在。因爲我剛剛獲得了我的更新代碼,並且在同一個類上有兩個名稱。我不知道該怎麼做。 @nnnnnn – Beginner

回答

0

好吧,我想你在代碼中的一些不準確之處:

  • 必須json的關鍵不同select小號各自的數據,你不能承擔其中的數據是訂單在JSON的地方總是對應於要素的順序在你的UI:

    res = JSON.parse(localStorage.getItem("testingvalue")); 
    
    // res now should be in form of 
    // res = { 
    // r1: { 
    //  qtyL: 2, 
    //  qtyO: 3, 
    // }, 
    // r2: { 
    //  ... 
    // }, 
    // ... 
    // }; 
    
  • 不應該硬編碼任何幻數到你的代碼,特別是如果它是關於JSON數據結構:

    var thunks = Object.keys(res).filter(function (name) { 
        return name.match(/^r(\d+)$/); 
    }); 
    console.log('found stat thunks:', thunks.join(', ')); 
    
    for (var r = 0; r < thunks.length; r++) { 
        var thunk = thunks[r]; 
        var stats = res[thunk]; 
        var els = document.querySelectorAll("." + thunk); 
        console.log('supplied stats for "' + thunk + '" thunk:', JSON.stringify(stats)); 
        console.log('found "<select>" elements:', els.length); 
        ... 
    
  • 你,或許,不應該假設,在用戶界面中的元素將被命名爲完全一樣的鍵持續的數據對象:

    // some ui-data bridge 
    function findSelectsByThunkName(name) { 
        if (name.match(/^r\d+$/)) { // stats thunk 
         return document.querySelectorAll("." + name); 
        } elseif (...) { 
         ... 
        } 
    
        return []; 
    } 
    
    ... 
    
    var thunks = Object.keys(res).filter(function (name) { 
        return name.match(/^r(\d+)$/); 
    }); 
    console.log('found stat thunks:', thunks.join(', ')); 
    
    for (var r = 0; r < thunks.length; r++) { 
        var thunk = thunks[r]; 
        var stats = res[thunk]; 
        var els = findSelectsByThunkName(thunk); 
        ... 
    

工作片段:

// jQuery has 'shortcut' for '$(document).ready(function() { ... });' 
 
// just use '$(function() { ... });' for simplicity's sake 
 
$(function(){ 
 
    var res = null; 
 

 
    try { 
 
    // assuming 'testingvalue' contains something like '{"r1":{"qtyL": 2,"qtyO": 3,...},"r2":{...},"something":[...],"and_other":1212,..}' 
 
    res = { 
 
     "r1": { 
 
     "qtyL": 2, 
 
     "qtyO": 3, 
 
     }, 
 
     "r2": { 
 
     }, 
 
     "something": [], 
 
     "and_other":1212, 
 
    } 
 
    
 
    //res = JSON.parse(localStorage.getItem("testingvalue")); 
 

 
    var thunks = 
 
     // get all keys from 'res' object (will get something like ["r1", "r2", "something", "and_other", ...]) 
 
     Object.keys(res) 
 
     // and filter them to get only those... 
 
     .filter(function (name) { 
 
     return (
 
      name.match(
 
      // that starts (^ symbol) 
 
      // with "r" character 
 
      // and then have any digit (\d sequence), 
 
      // probably, even more than one (+ symbol) 
 
      // and then ends ($ symbol) 
 
      /^r(\d+)$/ 
 
      // this is called "regular expression" 
 
      // you can read more about regexp's on supplied link [1] 
 
     ) 
 
     ); 
 
     }); 
 
     
 
    // thunks variable now holds the list of "res" object keys, that are corresponding to "^r\d+$" pattern, like ["r1", "r2"] 
 
    
 
    // as 'array' variables in javascript are in fact objects, they support some convenient methods for array elements manipulation (like mentioned '.filter()' method) etc 
 
    
 
    // '.join()' is a method of 'array' objects, that concatenates stringified elements of the array, gluing them with provided glue-string, so ["r1", "r2", "r3"] becomes "r1, r2, r3" in this case 
 
    console.log('found stat thunks:', thunks.join(', ')); 
 

 
    // and also 'array' objects have '.length' property that contains current array length 
 
    // we can use it to iterate over all actual elements 
 
    // of array, instead of hard-coding expected array length, which is somewhat ureliable 
 
    for (var r = 0; r < thunks.length; r++) { 
 
     var thunk = thunks[r]; // take key from list (remember, that array element indices are starting from 0) 
 
     var stats = res[thunk]; // now we can access a stats list from 'res' object by picked key 
 
     
 
     // now we can get the list of 'select' nodes on our page by their selectors 
 
     // ".class-name" in selector below actually means 
 
     // find all elements on page ('document'), that have "class-name" class ("class-name" is specified in their "class" atribute) 
 
     // mentioned "class-name" should only "occur at least once" in 'class' attribute, strict match isn't required, so ".r1" selector will match both <select class="r1"> and <select class="some-other-class r1 and-other and-another"> the same 
 
     // more you can read on the provided link [2] 
 
     var els = document.querySelectorAll("." + thunk); 
 
     
 
     // btw, beware that '.querySelectorAll()' returns 'NodeList' object, not the 'Array'. It also have '.length' property (like regular arrays) and it's elements can be accessed via bracket-index array access syntax ('els[index]'), but it doesn't have the same convenience mathods, as regular array objects (so, you can't, for example, filter it with 'els.filter()') 
 

 
     // print data to developer console for debugging 
 
console.log('supplied stats for "' + thunk + '" thunk:', JSON.stringify(stats)); 
 
     console.log('found "<select>" elements:', els.length); 
 
     
 
     // iterate over found 'select' elements 
 
     for (var i = 0; i < els.length; i++) { 
 
     var select = els[i]; 
 
     
 
     // '.getAttribute(attributeName)' returns value of any attribute of html node, 
 
     // for example, for html, supplied in the example, it will return "qtyL" and "qtyO" as "name" attributes for provided 'select' html nodes 
 
     var name = select.getAttribute("name"); 
 
     
 
     // we can use that "name" as key to access stat indexes from "res" object without relying, that stats in that object are listed and persisted in the same order, in which we are placing our 'select' elements in the page html code, and in which they were fetched and returned by '.querySelectorAll()' method. 
 
     select.selectedIndex = +stats[name]; 
 
     } 
 
    } 
 
    } catch (error){ 
 
    console.log(error.message); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr class="info" id="alertr1"> 
 
    <td width="30px">1</td> 
 
    <td width="200px">Likes Authority</td> 
 
    <td width="75px;"> 
 
     <select class="test-select r1" style="position: absolute; z-index:9999;" onmouseover="this.size=this.options.length" onmouseout="this.size=1" onchange="this.size=1" name="qtyL"> 
 
      <option value="0">-</option> 
 
      <option value="1">1</option> 
 
      <option value="2">2</option> 
 
      <option value="3">3</option> 
 
      <option value="4">4</option> 
 
     </select> 
 
    </td> 
 
    <td width="200px">Enthusiastic</td> 
 
    <td width="75px;"> 
 
     <select class="test-select r1" style="position: absolute; z-index:9999;" onmouseover="this.size=this.options.length" onmouseout="this.size=1" onchange="this.size=1" name="qtyO"> 
 
      <option value="0">-</option> 
 
      <option value="1">1</option> 
 
      <option value="2">2</option> 
 
      <option value="3">3</option> 
 
      <option value="4">4</option> 
 
     </select> 
 
    </td> 
 
    </tr> 
 
</table>

相關鏈接:

  1. Doc on regular expressions
  2. Doc on Css selectors
+0

您的聲明真的對我有用。感謝,我會盡我所能研究它,儘管你的代碼看起來很複雜:) – Beginner

+1

@Beginner,不客氣。如果你願意的話,我可以添加逐行解釋。那麼,我認爲你認爲複雜的唯一部分可能是這個'Ob​​ject.keys(res).filter()'?剩下的幾乎和你的一樣,減去'console.log()'語句... – ankhzet

+0

是的,過濾器是什麼意思? :O – Beginner

相關問題