如何创建动态更改HTML内容的切换按钮?

7 html javascript jquery

我已经在这个问题上工作了好几天,并且已经在SO和网络上进行了研究,并且无法找到帮助我解决它的材料.

我正在尝试创建一个天气应用程序,可以切换华氏温度和摄氏温度之间显示的天气单位.我首先在Fahrenheit中附加天气,然后我创建了一个事件处理程序,它根据该元素当前是显示"F"还是"C"来有条件地更改相关元素的内部内容.

事实上,我的应用程序成功加载了华氏温度,并在点击时切换到摄氏温度,但它不会切换回华氏温度.我认为事件的注册方式存在一些问题,但对于我的生活,我无法弄明白.

这是我的代码:

var fahr = document.createElement("a");
fahr.attr = ("href", "#");
fahr.className = "tempUnit";
fahr.innerHTML = tempf + "&deg;F" + "<br/>";
$("#currentWeather").append(fahr);

var cels = document.createElement("a");
cels.attr = ("href", "#");
cels.className = "tempUnit";
cels.innerHTML = tempc + "&deg;C" + "<br/>";

var units = document.getElementsByClassName("tempUnit");

$(".tempUnit").click(function() {
    if (units[0].innerHTML.indexOf("F") != -1) {
        $(".tempUnit").replaceWith(cels);
    } else {
        $(".tempUnit").replaceWith(fahr);
    }
})
Run Code Online (Sandbox Code Playgroud)

非常感谢你提前!如有必要,很乐意提供更多信息.

Sat*_*pal 5

目前您正在使用的是一种直接绑定,它只会在您的代码进行事件绑定调用时附加到页面上存在的元素.

在使用时replaceWith(),现有元素将替换为新元素,并且事件处理程序不会附加它们.

您需要使用.on()委托事件方法来使用事件委派.

一般语法

$(parentStaticContainer).on('event','selector',callback_function)
Run Code Online (Sandbox Code Playgroud)

示例,也使用thisie当前元素上下文和用于setAttribute()更新href元素

$("#currentWeather").on("click", ".tempUnit", function() {
      if (this.innerHTML.indexOf("F") != -1) {
        $(this).replaceWith(cels);
      }
      else {
        $(this).replaceWith(fahr);
      }
})
Run Code Online (Sandbox Code Playgroud)

var tempf = 212;
var tempc = 100;

var fahr = document.createElement("a");
fahr.setAttribute("href", "#");
fahr.className = "tempUnit";
fahr.innerHTML = tempf + "&deg;F" + "<br/>";
$("#currentWeather").append(fahr);

var cels = document.createElement("a");
cels.setAttribute("href", "#");
cels.className = "tempUnit";
cels.innerHTML = tempc + "&deg;C" + "<br/>";

$("#currentWeather").on("click", ".tempUnit", function() {
  if (this.innerHTML.indexOf("F") != -1) {
    $(this).replaceWith(cels);
  } else {
    $(this).replaceWith(fahr);
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="currentWeather"></div>
Run Code Online (Sandbox Code Playgroud)

  • @fbliss,很高兴我可以帮忙:) (2认同)