几天来我一直在研究这个问题,并在 SO 和整个网络上对其进行了研究,但无法找到帮助我解决它的 Material 。
我正在尝试创建一个天气应用程序,它可以在华氏度和摄氏度之间切换显示的天气单位。我首先附加华氏度的天气,然后我创建了一个事件处理程序,它根据该元素当前显示的是“F”还是“C”有条件地更改关联元素的内部内容。
实际上,我的应用成功加载了华氏温度,并在点击时切换到摄氏温度,但它不会切换回华氏温度。我假设事件的注册方式存在一些问题,但就我的生活而言,我无法弄清楚。
这是我的代码:
var fahr = document.createElement("a");
fahr.attr = ("href", "#");
fahr.className = "tempUnit";
fahr.innerHTML = tempf + "°F" + "<br/>";
$("#currentWeather").append(fahr);
var cels = document.createElement("a");
cels.attr = ("href", "#");
cels.className = "tempUnit";
cels.innerHTML = tempc + "°C" + "<br/>";
var units = document.getElementsByClassName("tempUnit");
$(".tempUnit").click(function() {
if (units[0].innerHTML.indexOf("F") != -1) {
$(".tempUnit").replaceWith(cels);
} else {
$(".tempUnit").replaceWith(fahr);
}
})
非常感谢您!如有必要,很乐意提供更多信息。
最佳答案
目前您使用的是直接绑定(bind),它只会附加到您的代码进行事件绑定(bind)调用时页面上存在的元素。
当您使用 replaceWith()
时,现有元素会被新元素替换,并且事件处理程序不会附加到它们。
您需要使用 Event Delegation使用 .on()委托(delegate)事件方法。
一般语法
$(parentStaticContainer).on('event','selector',callback_function)
示例,也使用this
即当前元素上下文并使用setAttribute()
更新 href
元素
$("#currentWeather").on("click", ".tempUnit", function() {
if (this.innerHTML.indexOf("F") != -1) {
$(this).replaceWith(cels);
}
else {
$(this).replaceWith(fahr);
}
})
var tempf = 212;
var tempc = 100;
var fahr = document.createElement("a");
fahr.setAttribute("href", "#");
fahr.className = "tempUnit";
fahr.innerHTML = tempf + "°F" + "<br/>";
$("#currentWeather").append(fahr);
var cels = document.createElement("a");
cels.setAttribute("href", "#");
cels.className = "tempUnit";
cels.innerHTML = tempc + "°C" + "<br/>";
$("#currentWeather").on("click", ".tempUnit", function() {
if (this.innerHTML.indexOf("F") != -1) {
$(this).replaceWith(cels);
} else {
$(this).replaceWith(fahr);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="currentWeather"></div>
关于javascript - 如何创建一个动态改变 HTML 内容的切换按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078885/