【问题标题】:Toggle button works in one direction only切换按钮仅在一个方向上起作用
【发布时间】:2017-11-28 21:01:15
【问题描述】:

我的切换按钮逻辑(<script> 标签下的最后一个代码块)似乎只在一个方向上工作。具体来说,温度变量temp 以摄氏度到达这部分代码。单击按钮后,一切都成功转换为华氏温度,但随后按钮停止工作。请注意,我尝试了使用闭包的替代设计,将所有内容嵌入到 updateTemp 函数中,每次单击时更改按钮的 id,并取消$(document).ready 下的前两个变量。这是一团糟,仍然没有提供我正在寻找的切换功能。想法?

<!DOCTYPE html>

<html lang="en">
    <head>
        <!-- Bootstrap -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <!-- CSS -->

        <!-- JS/JQ -->
        <script>
        $(document).ready(function () {
            var tempType = 0;
            var temp = 0;
            var coords = {
              lat: 0,
              lon: 0
            };
            // retrieve and set user's latitude and longitude coordinates
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    coords.lon = position.coords.longitude;
                    coords.lat = position.coords.latitude;
                    // AJAX called here b/c getCurrentPosition is asynchronous
                    sendAJAX(coords);
                });
            } else {
                alert("Sorry, I couldn't locate you. Here's the weather elsewhere.");
                coords.lon = 48.8566;
                coords.lat = 2.3522;
                sendAJAX(coords);
            }
            // AJAX request and settings wrapped in fxn for ease of calling within if/else
            function sendAJAX (coords) {
                // enumerate AJAX request settings & pass in coordinate settings
                var ajaxOptions = {
                    crossDomain:true,
                    dataType:"json",
                    url:"https://fcc-weather-api.glitch.me/api/current?",
                    data: {
                        lon:coords.lon,
                        lat:coords.lat
                    },
                    method:"GET"
                };
                // attached .done() fxn calls used here, as they rely on the JSON file returned by the AJAX request
                $.ajax(ajaxOptions).done(updateCity).done(updateIcon).done(updateDesc).done(updateTemp).done(updateHumid).done(updateWind);
            }
            // update weather icon on page
            function updateCity (json) {
                var cityHTML = "";
                cityHTML += json.name + ", " +  json.sys.country;
                $("#city").html(cityHTML);
            }
            // update weather icon on page
            function updateIcon (json) {
                var iconHTML = "";
                iconHTML += "<img src='" + json.weather[0].icon + "'";
                iconHTML += "alt='weather icon'>";
                $("#icon").html(iconHTML);
            }
            // update description of weather on page
            function updateDesc (json) {
                var descHTML = "";
                var desc = json.weather[0].main;
                descHTML += desc;
                $("#descript").html(descHTML);
                changeImage(desc);
            }
            // update temperature
            function updateTemp (json) {
                var tempHTML = "";
                // the 0x in front of the character code matters, no truncation allowed despite what some docs might seem to suggest
                temp = Math.round(json.main.temp);
                var degree = String.fromCharCode(0x2103);
                tempHTML += temp + degree;
                $("#temp").html(tempHTML);

            }
            // update humidity
            function updateHumid (json) {
                var humidHTML = "";
                var percent = String.fromCharCode(0x0025);
                humidHTML += json.main.humidity + percent;
                $("#humidity").html(humidHTML);
            }
            // update wind speed
            function updateWind (json) {
                var windHTML = "";
                windHTML += json.wind.speed + " knots";
                $("#wind").html(windHTML);
            }
            // change background image
            function changeImage (desc) {
                if (desc.match(/Clear/)) {
                    $("body").css("background-image", "url(img/clear.jpg)");
                } else if (desc.match(/Rain/)) {
                    $("body").css("background-image", "url(img/rain.jpg)");
                } else if (desc.match(/Haze/)) {
                    $("body").css("background-image", "url(img/haze.jpg)");
                } else if (desc.match(/Clouds/)) {
                    $("body").css("background-image", "url(img/cloudy.jpg)");
                } else if (desc.match(/Snow/)) {
                    $("body").css("background-image", "url(img/snow.jpg)");
                } else {
                    $("body").css("background-image", "url(img/default.jpg)");
                }
            }
            // toggle button logic
            if (tempType == "0") {
                $("#convert").on("click", function () {
                    var fahrenheit = Math.round((9/5)*(temp) + 32);
                    var tempFarHTML = "";
                    var degree = String.fromCharCode(0x2109);
                    tempFarHTML += fahrenheit + degree;
                    $("#temp").html(tempFarHTML);
                    $("#convert").html("Convert to Celsius");
                    tempType == "1";
                });
            } else {
                $("#convert").on("click", function () {
                    var celsius = temp;
                    var tempCelsiusHTML = "";
                    var degree = String.fromCharCode(0x2103);
                    tempCelsiusHTML += celsius + degree;
                    $("#temp").html(tempCelsiusHTML);
                    $("#convert").html("Convert to Celsius");
                    tempType == "0";
                });
            }

        });
        </script>
        <title>Local Weather</title>
    </head>
    <body>
        <div class="container">
            <div class="row text-center">
                <div id="page-title" class="col-md-12">
                    The Local Weather
                </div>
            </div>
            <div class="row text-center">
                <div id="city" class="col-md-12">
                    City
                </div>
            </div>
            <div class="row text-center">
                <h2>Current Conditions</h2>
                <div id="icon" class="col-md-12 img-responsive">
                    Icon
                </div>
                <div id="descript" class="col-md-12">
                    Desc
                </div>
            </div>
            <div class="row text-center">
                <div class="col-md-4">
                    <h2>Temperature</h2>
                </div>
                <div class="col-md-4">
                    <h2>Humidity</h2>
                </div>
                <div class="col-md-4">
                    <h2>Wind</h2>
                </div>
            </div>
            <div class="row text-center">
                <div id="temp" class="col-md-4">
                    Temp
                </div>
                <div id="humidity" class="col-md-4">
                    Humid
                </div>
                <div id="wind" class="col-md-4">
                    Wind
                </div>
            </div>
            <div class="row text-center">
                <div id="temp" class="col-md-4">
                    <button id="convert" class="btn btn-default">Convert to Fahrenheit</button>
                </div>
            </div>
        </div>
    </body>
</html>

【问题讨论】:

  • 您有一个重复的 id ("temp"),这会影响您的代码功能。
  • 思考 - 是否有任何控制台错误?当您放置断点并单步调试时,切换位置之间会发生什么不同?
  • 我最近学到的一些技巧也帮助我清理了我的代码。不要使用 html id 来识别元素,而是使用数据属性data-el="temp" 这可以让您将 html/css 与 js 完全分开。此外,在您的 js 中,在顶部定义 html 元素,例如var tempElement = '[data-el="temp"]' 这使得将来进行更新变得容易,而且您不会重复代码。最后,考虑使用 let 来代替 var;这是 ES6 语法,适用于所有更新的浏览器,但不适用于旧浏览器,因此如果您需要支持旧浏览器,则需要进行转译。

标签: javascript jquery


【解决方案1】:

应在函数内部检查条件如下:

            // toggle button logic

                $("#convert").on("click", function () {
                    if (tempType == "0") {
                        var fahrenheit = Math.round((9/5)*(temp) + 32);
                        var tempFarHTML = "";
                        var degree = String.fromCharCode(0x2109);
                        tempFarHTML += fahrenheit + degree;
                        $("#temp").html(tempFarHTML);
                        $("#convert").html("Convert to Celsius");
                        tempType == "1";
                        temp = fahrenheit;
                    } else {
                        var celsius = temp;
                        var tempCelsiusHTML = "";
                        var degree = String.fromCharCode(0x2103);
                        tempCelsiusHTML += celsius + degree;
                        $("#temp").html(tempCelsiusHTML);
                        $("#convert").html("Convert to Celsius");
                        tempType == "0";
                        temp = celsius
                    });
                });

另外,正如@gavgrif 在对该问题的评论中提到的,有一个重复的 id “temp”,应该更正。

【讨论】:

    【解决方案2】:

    代替

    tempType == "1";
    

    我认为您正在寻找一个等号

    tempType = "1";
    

    【讨论】:

    • 是的。当我查看上面的答案时,我注意到了这一点。现在 tempType 更新了,但仍然没有从华氏温度转换回摄氏温度。
    【解决方案3】:

    当您的页面加载时,您的 tempType 为 0,并且在您的转换 div 上注册了点击事件以将值更改为 farenheit。

    当 onClick 事件被触发并且您的转换第一次工作时,您的 onClick 事件不会改变,因为您的页面没有再次加载并且您的 onClick 事件保持不变,即使您的 tempType em> 设置为 1。您需要更改尝试解决问题的方式,您必须重新加载整个页面或创建一个更改 onClick 事件的函数,并将其分配给您的按钮,但这不是一个好习惯并且会被认为是一种反模式。最好的方法是在 onClick 事件中移动 if-else 条件。

    【讨论】:

    • 我一直和你在一起,直到“创建一个改变你的 onClick 事件的函数”——我认为这是一个反模式。您应该首选在 onClick 事件中移动条件的最终建议。
    • @thisguyheisaguy 我同意你的看法。我只是想列出所有的可能性。我将编辑我的答案以指出这一点。
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多