2017-05-19 3 views
-1

Ich hatte eine Klasse mit zwei Namen, die Klasse ist = test-select r10 und ich habe zehn Zeilen davon. Zum Beispiel:Wie bekomme ich geteilelementbyClassname die Klasse enthält 2 Namen?

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>

Wie kann ich den zweiten Namen der Klasse mit getelementByClassName bekommen ??

+5

Sie keine Klasse mit zwei Namen haben, haben Sie Elemente mit zwei verschiedenen Klassen. Fragen Sie, wie man Elemente auswählt, die die zweite Klasse haben, oder wie man den Namen der zweiten Klasse anhand des ersten Klassennamens herausfinden kann? Oder...? – nnnnnn

+0

Sie können den Klassennamen in einer js-Variablen speichern und/loop/auswählen, mit welchem ​​Element oder untergeordneten Elementen Sie arbeiten möchten. – CodeMonkey

+0

Fragen Sie, wie Sie Elemente auswählen, die die zweite Klasse haben - Ja, das ist die Frage. Weil ich gerade meinen aktualisierten Code bekommen habe, und es gibt 2 Namen in derselben Klasse. Ich habe keine Ahnung, was ich tun soll. @nnnnnn – Beginner

Antwort

0

Okay, ich nehme an, Sie haben einige Ungenauigkeiten in dem Code:

  • Sie Muss verschiedene select s jeweiligen Daten in json durch Schlüssel, Sie nicht nehmen die Reihenfolge, in der Daten Orte in json werden immer auf der Reihenfolge der Elemente in Ihrem UI entsprechen:

    res = JSON.parse(localStorage.getItem("testingvalue")); 
    
    // res now should be in form of 
    // res = { 
    // r1: { 
    //  qtyL: 2, 
    //  qtyO: 3, 
    // }, 
    // r2: { 
    //  ... 
    // }, 
    // ... 
    // }; 
    
  • Sie sollte nicht hard irgendwelche magischen Zahlen in Ihren Code, vor allem, wenn es um json Datenstruktur ist:

    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); 
        ... 
    
  • Sie wahrscheinlich sollte nicht annehmen, dass Ihre Elemente in UI wird genau wie Schlüssel genannt werden in beharrte Datenobjekte:

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

Arbeits snippet:

// 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>

Nützliche Links:

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

Ihre Aussage war wirklich nützlich für mich.Vielen Dank und ich werde es mit meinen besten Bemühungen studieren, obwohl Ihr Code für mich kompliziert aussehen :) – Beginner

+1

@Beginner, Gern geschehen. Ich kann dem Code Code für Zeile hinzufügen, wenn Sie möchten. Nun, der einzige Teil, den Sie für kompliziert halten, könnte dieser 'Object.keys (res) .filter()' sein? Der Rest ist fast identisch mit Ihrem, minus 'console.log()' Anweisungen ... – ankhzet

+0

Ja, was bedeutet der Filter? : O – Beginner

Verwandte Themen