无法在onclick上更改文本

时间:2022-11-13 19:09:13

I have a codepen at http://codepen.io/templenaylor/pen/ggoMPZ?editors=0011

我在http://codepen.io/templenaylor/pen/ggoMPZ?editors=0011上有一个codepen

I am currently displaying a temperature that references a var:

我目前正在显示一个引用var的温度:

<ul>
  <li id="fTemp"></li>
</ul>

When trying to change it by clicking it, it will not work. This is the function I am using to do that:

尝试通过单击更改它时,它将无法正常工作。这是我用来做的功能:

  $("#fTemp").click(function(){
    if(tempSwap===false){
      $("#fTemp").html(fTemp + " &#8457;");
      tempSwap=true;
    } else{
      $("fTemp").html(cTemp + " &#8451;");
      tempSwap=false;
    }
  });

Is there something I am not seeing within my function that is incorrect?

我的功能中有没有看到不正确的东西?

2 个解决方案

#1


4  

As pointed out by @MichaelCoker, you are missing the # in your else branch.

正如@MichaelCoker所指出的那样,你错过了你的其他分支中的#。

In addition to fixing that, I would save the element to a variable to help prevent errors in the future.

除了修复它,我会将元素保存到变量,以帮助防止将来出错。

var ftemp_li = $("#fTemp");

ftemp_li.click(function(){
  if(tempSwap == false){
    ftemp_li.html(fTemp + " &#8457;");
    tempSwap = true;
  } else {
    ftemp_li.html(cTemp + " &#8451;");
    tempSwap = false;
  }
});

http://codepen.io/anon/pen/VPyNPO?editors=0011

#2


3  

You are not referencing the correct selector in your else block

您没有在else块中引用正确的选择器

} else{
      $("fTemp").html(

is supposed to be

应该是

} else{
      $("#fTemp").html(

Also you seem to binding the click event every single time your ajax is successful.

此外,您似乎每次ajax成功时绑定click事件。

Move it out of the callback and bind your click event in DOM ready handler.

将其移出回调并将您的click事件绑定到DOM ready处理程序中。

#1


4  

As pointed out by @MichaelCoker, you are missing the # in your else branch.

正如@MichaelCoker所指出的那样,你错过了你的其他分支中的#。

In addition to fixing that, I would save the element to a variable to help prevent errors in the future.

除了修复它,我会将元素保存到变量,以帮助防止将来出错。

var ftemp_li = $("#fTemp");

ftemp_li.click(function(){
  if(tempSwap == false){
    ftemp_li.html(fTemp + " &#8457;");
    tempSwap = true;
  } else {
    ftemp_li.html(cTemp + " &#8451;");
    tempSwap = false;
  }
});

http://codepen.io/anon/pen/VPyNPO?editors=0011

#2


3  

You are not referencing the correct selector in your else block

您没有在else块中引用正确的选择器

} else{
      $("fTemp").html(

is supposed to be

应该是

} else{
      $("#fTemp").html(

Also you seem to binding the click event every single time your ajax is successful.

此外,您似乎每次ajax成功时绑定click事件。

Move it out of the callback and bind your click event in DOM ready handler.

将其移出回调并将您的click事件绑定到DOM ready处理程序中。