简体   繁体   English

jQuery Toggle无法使用多个元素

[英]jQuery Toggle not working with multiple elements

I want to make a toggle functionality using very simple code of jQuery 我想使用非常简单的jQuery代码制作切换功能

On load of page temperature will be displayed in Celsius and If I clicked on that temperature text another variable holding temperate in Fahrenheit will appear. 在页面加载时,温度将以摄氏度显示,如果单击该温度文本,则会出现另一个以华氏度保持温度的变量。

Can anybody please help me, what mistake I am doing. 有人可以帮我吗,我在做什么错。

If I uncomment the alert function my code is working fine. 如果我取消注释alert功能,则我的代码可以正常工作。

<style>#fahrenn {display:none;}</style>



document.getElementById('temprature').innerHTML='<b>Temprature: </b><span id="celcioussss">'+minTemprtr+'&#8451; </span><span id="fahrenn">'+tempFar+'&#8457;</span>';


<script>
$(document).ready(function(){
  //alert();

    $("#celcioussss").click(function(){
    $(this).css("display","none");
    $("#fahrenn").toggle();
    });

    $("#fahrenn").click(function(){
    $(this).css("display","none");
    $("#celcioussss").toggle();
   });

});
</script>

It seems that you're appending HTML dynamically from JS. 看来您是从JS动态附加HTML。

If your HTML is dynamically appended in body using JS, then you need to bind the event to the particular element to make it working. 如果使用JS将HTML动态附加到正文中,则需要将事件绑定到特定元素以使其起作用。

$(document).on('click', '#celcioussss', function(){
    $(this).css("display","none");
    $("#fahrenn").toggle();
});

$(document).on('click', "#fahrenn", function(){
    $(this).css("display","none");
    $("#celcioussss").toggle();
});

More information .on() 有关更多信息.on()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM