如何获取该类包含2个名称的getelementbyClassname?

时间:2017-05-19 07:20:51

标签: javascript getelementsbyclassname

我有一个有两个名字的班级,即class = test-select r10,我有十行。例如:



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];
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

如何使用getelementByClassName ??

获取类的第二个名称

1 个答案:

答案 0 :(得分:0)

好的,我猜你在代码中有一些不准确之处:

  • 必须<{1}} select分别在json中的相应数据,您无法承担订单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);
      ...
    
  • 您可能不应该假设您的UI中的元素的名称与持久数据对象中的键完全相同:

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

工作片段:

&#13;
&#13;
// 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);
  }
});
&#13;
<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>
&#13;
&#13;
&#13;

有用的链接:

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