如何在JavaScript函数中为表分配类或ID?

时间:2016-04-02 13:08:25

标签: javascript html mysql css json

我必须使用HTML,CSS和JavaScript(所以没有jQuery)。

我创建了一个通过API接收JSON数据的表。我有一个功能来通过单击复选框来显示/隐藏每个表行。我已经包含了JavaScript函数,但我无法弄清楚在哪里放置类或id,所以我可以将函数连接到每个表行。一般来说,我会向<td>添加一个类,例如:<td class="example">但在这种情况下它不起作用。我执行此操作时代码中断了。

我在线搜索了几个小时,但未能找到答案。我不是在寻找完成的代码,而是一个提示/帮助如何实现这一点。

此表使用以下方式创建:

body {
    background: white;
}

h1 {
    color: black;
    font-size: 35px;
    text-align: center;
    font-family: 'Quicksand', sans-serif;
}

h2 {
    font-family: 'Quicksand', sans-serif;
    margin-left: 3.3em;
}

table, th , td {
    border: none;
    border-collapse: collapse;
    padding: 15px; 
    margin-left: 5em;
    margin-top: -25em;
}


table tr:nth-child(odd) {
    background-color: #f1f1f1;
}
table tr:nth-child(even) {
    background-color: #ffffff;
}
  
#form {
    font-family: 'Quicksand', sans-serif;
    margin-left: 5em;
}

#googleMap {
    margin-left: 45em;;
    margin-right: auto;
}

#chkbox_display {
    margin-left: 5em;
    margin-top: 3em;
    font-family: 'Quicksand', sans-serif;
}

.hidden {
    display: none;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css"> 
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
    
<title>Weather App</title>    
</head>
    
    
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>    

<h2>Please enter the following information:</h2>    
<form id="form" onsubmit ="return fetchUrl()">
    Enter your City:<br>
    <input id="weather_city" placeholder="Entere here..."><br>
    How to display values: <br>
    <select id="weather_scale">
        <option value="Metric">Metric Units (Celcius/mm)</option>
        <option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
    </select><br>
    Number of days to show weather:<br>
    <select id="weather_numberOfDays">
        <option value="1">Today only</option>
        <option value="2">2 days</option>
        <option value="3">3 days</option>
        <option value="4">4 days</option>
        <option value="5">5 days</option>
    </select>
    <br><br>
    <button onclick="initialize">Submit</button>
        </form>


<div id="chkbox_display">
<form action="#">
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Max. Temp.</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Min. Temp</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Rainfall</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Pressure</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Humidity</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Wind Speed</label>
    </form>  
</div>
    
<script>
    
function initAutocomplete() {

    weather_city = new google.maps.places.Autocomplete(
    (document.getElementById('weather_city')),
    {types: ['geocode']});
    weather_city.addListener('place_changed');
}
        
    </script>    
    
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>

<script>
    
    var longitude;
    var latitude;
    
function initalize(arr) {    
    var lon = arr.city.coord.lon;
    var lat = arr.city.coord.lat;
    
    var mapProp = {
    center:new google.maps.LatLng(lat,lon),
    zoom:10,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
    
</script>


<div id="googleMap" style="width:600px;height:480px;"></div>
 

<section>
    <div id="table"> 
<!--
    <tr>
        <td class="hidden">example</td>
        <td class="hidden"></td>
        <td class="hidden"></td>
    </tr>    
-->
    
    </div>
    </section>   
    
<script> 
    
function getJson(request) {
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", request, true);
    xmlhttp.send();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);  
    }
}
}

function fetchUrl() {
    var form = document.getElementById("form");
    var city = form.weather_city.value;
    var value = form.weather_scale.value;
    var days = form.weather_numberOfDays.value;
    
    var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
    
    getJson(url);
    return false;
}
    
function myFunction(response) {
    var arr = JSON.parse(response);
    initalize(arr);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.list.length; i++) {
        out += "<tr><td>" +
        new Date(arr.list[i].dt * 1000) +
        "</td></tr>" +
        "<tr><td>" +
        getIcon(arr.list[i].weather[0].icon) +
        "</td><td>" +
        arr.list[i].weather[0].description +
        "</td><tr>" +
        "</tr><td>" +
        "Min. Temperature" +
        "</td><td>" +
        arr.list[i].temp.min +
        "</td><tr>" +
        "</tr><td>" +
        "Max. Temperature" +
        "</td><td>" +
        arr.list[i].temp.max +
        "</td><tr>" +
        "</tr><td>" +
        "Pressure" +
        "</td><td>" +
        arr.list[i].pressure +
        "</td><tr>" +
        "</tr><td>" + 
        "Windspeed" +
        "</td><td>" +
        arr.list[i].speed +
        "</td><tr>" +
        "</tr><td>" + 
        "Humidity" +
        "</td><td>" +
        arr.list[i].humidity +
        "</td><tr>" +
        "</tr><td>" +   
        "Predicted Rainfall" +
        "</td><td>" +
        arr.list[i].rain +
        "</td><td>";
    }
    out += "</table>";
    document.getElementById("table").innerHTML = out;
}
    
function getIcon(s) {
    return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
    
</script>   
    
<script>
    //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
    function showHide() {
        var checkbox = document.getElementById("chkbox");
        var hiddenInput = document.getElementsByClassName("hidden");
        
        for(var i = 0; i !=hiddenInput.length; i++) {
            if(checkbox.checked) {
                hiddenInput[i].style.display = "inline";
            } else {
                hiddenInput[i].style.display = "none";
            }
            }
        }
    </script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

根据当前的方法,实现这一目标的最简单方法是转换<td>开头标记的HTML:

"<tr><td>"

为:

"<tr><td class='example'>"

然后使用CSS来设置相关元素的样式,例如:

.example {
  color: #f90;
}

或者,一旦您分配了innerHTML字符串,就可以添加以下内容:

// retrieves the collection of <td> elements from within the
// element with the id of 'table', and uses Array.from() to
// convert that collection into an Array.
// Then iterates over the array of elements using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
  // within the anonymous function the 'td' argument is a reference
  // to the current array-element of the array over which we're
  // iterating.

  // here we use the Element.classList API to add the 'example'
  // class-name to the existing (if any) class-names of the <td>
  // elements:
  td.classList.add('example');
});

body {
    background: white;
}

h1 {
    color: black;
    font-size: 35px;
    text-align: center;
    font-family: 'Quicksand', sans-serif;
}

h2 {
    font-family: 'Quicksand', sans-serif;
    margin-left: 3.3em;
}

table, th , td {
    border: none;
    border-collapse: collapse;
    padding: 15px; 
    margin-left: 5em;
    margin-top: -25em;
}


table tr:nth-child(odd) {
    background-color: #f1f1f1;
}
table tr:nth-child(even) {
    background-color: #ffffff;
}
  
#form {
    font-family: 'Quicksand', sans-serif;
    margin-left: 5em;
}

#googleMap {
    margin-left: 45em;;
    margin-right: auto;
}

#chkbox_display {
    margin-left: 5em;
    margin-top: 3em;
    font-family: 'Quicksand', sans-serif;
}

.hidden {
    display: none;
}

.example {
  color: #f90;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css"> 
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
    
<title>Weather App</title>    
</head>
    
    
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>    

<h2>Please enter the following information:</h2>    
<form id="form" onsubmit ="return fetchUrl()">
    Enter your City:<br>
    <input id="weather_city" placeholder="Entere here..."><br>
    How to display values: <br>
    <select id="weather_scale">
        <option value="Metric">Metric Units (Celcius/mm)</option>
        <option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
    </select><br>
    Number of days to show weather:<br>
    <select id="weather_numberOfDays">
        <option value="1">Today only</option>
        <option value="2">2 days</option>
        <option value="3">3 days</option>
        <option value="4">4 days</option>
        <option value="5">5 days</option>
    </select>
    <br><br>
    <button onclick="initialize">Submit</button>
        </form>


<div id="chkbox_display">
<form action="#">
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Max. Temp.</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Min. Temp</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Rainfall</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Pressure</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Humidity</label>
    
    <input type="checkbox" name="chkbox" id="chkbox"/>
    <label for="chkbox">Wind Speed</label>
    </form>  
</div>
    
<script>
    
function initAutocomplete() {

    weather_city = new google.maps.places.Autocomplete(
    (document.getElementById('weather_city')),
    {types: ['geocode']});
    weather_city.addListener('place_changed');
}
        
    </script>    
    
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>

<script>
    
    var longitude;
    var latitude;
    
function initalize(arr) {    
    var lon = arr.city.coord.lon;
    var lat = arr.city.coord.lat;
    
    var mapProp = {
    center:new google.maps.LatLng(lat,lon),
    zoom:10,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
    
</script>


<div id="googleMap" style="width:600px;height:480px;"></div>
 

<section>
    <div id="table"> 
<!--
    <tr>
        <td class="hidden">example</td>
        <td class="hidden"></td>
        <td class="hidden"></td>
    </tr>    
-->
    
    </div>
    </section>   
    
<script> 
    
function getJson(request) {
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", request, true);
    xmlhttp.send();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);  
    }
}
}

function fetchUrl() {
    var form = document.getElementById("form");
    var city = form.weather_city.value;
    var value = form.weather_scale.value;
    var days = form.weather_numberOfDays.value;
    
    var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
    
    getJson(url);
    return false;
}
    
function myFunction(response) {
    var arr = JSON.parse(response);
    initalize(arr);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.list.length; i++) {
        out += "<tr><td>" +
        new Date(arr.list[i].dt * 1000) +
        "</td></tr>" +
        "<tr><td>" +
        getIcon(arr.list[i].weather[0].icon) +
        "</td><td>" +
        arr.list[i].weather[0].description +
        "</td><tr>" +
        "</tr><td>" +
        "Min. Temperature" +
        "</td><td>" +
        arr.list[i].temp.min +
        "</td><tr>" +
        "</tr><td>" +
        "Max. Temperature" +
        "</td><td>" +
        arr.list[i].temp.max +
        "</td><tr>" +
        "</tr><td>" +
        "Pressure" +
        "</td><td>" +
        arr.list[i].pressure +
        "</td><tr>" +
        "</tr><td>" + 
        "Windspeed" +
        "</td><td>" +
        arr.list[i].speed +
        "</td><tr>" +
        "</tr><td>" + 
        "Humidity" +
        "</td><td>" +
        arr.list[i].humidity +
        "</td><tr>" +
        "</tr><td>" +   
        "Predicted Rainfall" +
        "</td><td>" +
        arr.list[i].rain +
        "</td><td>";
    }
    out += "</table>";
    document.getElementById("table").innerHTML = out;
  
  Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
    td.classList.add('example');
  });
}
    
function getIcon(s) {
    return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
    
</script>   
    
<script>
    //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
    function showHide() {
        var checkbox = document.getElementById("chkbox");
        var hiddenInput = document.getElementsByClassName("hidden");
        
        for(var i = 0; i !=hiddenInput.length; i++) {
            if(checkbox.checked) {
                hiddenInput[i].style.display = "inline";
            } else {
                hiddenInput[i].style.display = "none";
            }
            }
        }
    </script>

</body>
</html>

当然,这确实假设您需要将类名附加到元素上是正确的;没有解释你试图通过添加类名解决的问题,很难提供更好的建议。

答案 1 :(得分:-1)

我建议您使用'knockoutjs'通过返回的Json数据填充表格。为了您的目的,它非常适合。它绝对容易学习。如果您对此方法感兴趣,可以在评论中向我提问。我会尽力帮助您解决您的特定问题。

参考:Knockout tutorial