gpt4 book ai didi

javascript - 单击图标后更新 html 内容

转载 作者:太空宇宙 更新时间:2023-11-04 09:21:00 25 4
gpt4 key购买 nike

点击摄氏度或华氏度图标后,我想更改度数和图标。我怎么了,它只更新了一次。

html:

<ul id="list">
<li></li>
<li>&nbsp;<i class="wi wi-celsius"></i></li>
<li></li>
</ul>

JS:

$('#list li:nth-child(2)>i').click(function() {
var temp = $('#list li:nth-child(2)');
if ($(this).hasClass('wi wi-celsius')) {
alert("C");
var convertedTemp = parseInt(temp.text()) * 9 / 5 + 32;
temp.html(Math.round(convertedTemp) + '&nbsp;<i class="wi wi-fahrenheit"></i>');

} else {
alert("F");
var convertedTemp = (parseInt(temp.text()) - 32) / (9 / 5);
temp.html(Math.round(convertedTemp) + '&nbsp;<i class="wi wi- celsius"></i>');
}
});

最佳答案

因为您从页面中删除了该元素。该事件不会连接到您添加的新元素。所以你需要使用事件委托(delegate)。

$('#list li:nth-child(2)').on("click", ">i" , function () {

另一种选择是不替换 HTML,只替换文本和类。

$('#list li:nth-child(2)>i').click(function() {
var icon = $(this).toggleClass("wi-celsius wi-fahrenheit"),
li = icon.closest("li"),
span = li.find("span"),
num = parseFloat(span.text()),
isCel = icon.hasClass('wi-celsius'),
val = isCel ? num * 9 / 5 + 32: (num - 32) * 5 / 9;
span.text(val);
});
.wi-celsius::after { 
cursor : pointer;
content : "°C"
}

.wi-fahrenheit::after {
cursor : pointer;
content : "°F"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="list">
<li></li>
<li><span class="num">32</span>&nbsp;<i class="wi wi-celsius"></i>
</li>
<li></li>
</ul>

关于javascript - 单击图标后更新 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41487083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com