2017-05-19 55 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

相关问题