代码之家  ›  专栏  ›  技术社区  ›  Cdhippen

Javascript通过单击我的按钮更改我的对象的值,但再次单击时,它不会切换回

  •  0
  • Cdhippen  · 技术社区  · 6 年前

    我已经设置了一个if | else if脚本,将项目上显示的温度从Celcius切换到Ferinheit,它可以正常工作。当我单击“C”时,它会进行数字转换,并在末尾附加“F”。然而,现在当我点击“F”时,它不会切换回来,我也不知道为什么。我尝试在函数之外声明变量,以防它们被覆盖,但这也不起作用。以下是JS代码(至少是与问题相关的部分):

            num = Math.round(parseInt(arr.main.temp));
            var temp = num+String.fromCharCode(176)+`<span class=\"temp\" id='ctof'>${tempValue}</span>`; 
            $("#temperature").html(temp)
            $('#ctof').click(function () {
              var currentTempUnit = tempValue;
              var newTempUnit = currentTempUnit == "C" ? "F" : "C";
              console.log(newTempUnit);
              tempValue = newTempUnit;
              if (newTempUnit == "F") {
                num = Math.round(parseInt(arr.main.temp * (9/5) + 32));
                var fahTemp = num+String.fromCharCode(176)+`<span class=\"temp\" id='ctof'>${tempValue}</span>`;
                $("#temperature").html(fahTemp)
              } else {
                $("#temperature").text(temp);
              }
    

    对于完整代码和CSS等,代码笔位于此处: https://codepen.io/chase-hippen/pen/WzqBvj?editors=0011

    4 回复  |  直到 6 年前
        1
  •  1
  •   kshetline    6 年前

    执行此操作时:

    $('#ctof').click(function ()...
    

    将该单击功能附加到 当前存在的 id为的DOM元素 ctof 。稍后创建具有相同id的新节点时,它不会自动拾取相同的事件侦听器。

    分离函数,以便可以在多个位置添加它,并确保在创建新节点时,再次添加侦听器。

    以下是您的代码的编辑版本: https://codepen.io/anon/pen/OvKVNX?editors=0011

        2
  •  1
  •   Dong Nguyen    6 年前

    ID为的元素 #ctof 是动态的。每次将其插入 #temperature ,事件( click )你已经附加到它将去。

        3
  •  0
  •   Blake Shadle    6 年前

    如果动态生成#ctof,则需要在文档级别附加click处理程序。例如:

    $(document).on("click", "#ctof", function() {
        // do your work here
    });
    
        4
  •  0
  •   AWP    6 年前

    当我添加一个id为“ctof”的div并单击它时,它工作得很好。

    <div id="ctof">click me to change temp</div>
    

    我觉得你的js很好。