jquery“this”用于函数问题

jquery“this”用于函数问题,jquery,Jquery,我正在编写一个基本的web应用程序,它有一些列表元素,我需要能够单击每个LI周围的整个LI来选择其中的单选按钮,并且只确保选中我单击的那个。我可以通过在.click回调中编写代码来实现这一点,但若我尝试从一个命名函数中调用相同的代码,它会崩溃,我相信这和我正在使用的引用有关,但我似乎无法修复它 HTML是 <ul> <form id="healthCheckAge" name="healthCheckAge"> <li> <input t

我正在编写一个基本的web应用程序,它有一些列表元素,我需要能够单击每个LI周围的整个LI来选择其中的单选按钮,并且只确保选中我单击的那个。我可以通过在.click回调中编写代码来实现这一点,但若我尝试从一个命名函数中调用相同的代码,它会崩溃,我相信这和我正在使用的引用有关,但我似乎无法修复它

HTML是

<ul> 
  <form id="healthCheckAge" name="healthCheckAge"> 
    <li> <input type="radio" name="eighteen" value="18-30" />18-30 </li> 
    <li> <input type="radio" name="thirtyone" value="31-45" />31-45 </li> 
    <li> <input type="radio" name="fourtysix" value="46-65" />46-65 </li> 
    <li> <input type="radio" name="sixtyfive" value="65+" />65+</li> 
  </form> 
</ul> 
我认为问题在于,当我把最后一个条件语句称为“this”时,它并没有反映出我需要什么


有什么想法吗?

只需将元素传递给函数:

function lol(element){
  //set the vars for the selectors
  var listInputs = $('#healthCheckAge li input');
  var clicked = listInputs.attr('name');
  //loop on all the li children to see if they match the clicked LI - if not ensure that they are unchecked and faded
  $(listInputs).each(function(index,Element){
    $(listInputs).attr('checked',false).parent().addClass('selected');
  });
  //set the radio button to checked and apply a style to it, while removing this from any other checked radio buttoon
  if($(listInputs).attr('name')==clicked){
    $(element).children().attr('checked','true').parent().removeClass('selected'); 
  } 
}
  $('#healthCheckAge li').click(function(){
    lol(this);                                
  });

在click处理程序中,这指的是元素,但在lol中,它指的是函数的所有者,即全局窗口对象。

您可以使用调用将lol的范围绑定到jQuery设置的对象,这是一种可用于所有函数的方法:

$('#healthCheckAge li').click(function(){
    lol.call(this);                                
});

请参见

最简单的方法是保持功能不变,并执行以下操作:

$('#healthCheckAge li').click( li_click );
现在,这是接收事件的元素,如果需要,您仍然可以在函数中定义事件参数


这完全等同于将函数作为参数直接传递给click方法。

您使用的是Firebug还是Chrome开发工具?我一直在为iPad开发,所以一直在使用Safari,尽管我有Chrome,这应该可以在那里使用。我一直在safari中运行jquery的JSLint,控制台抱怨没有找到带有选择器“undefined”的元素,如果我在中运行相同的代码,则不会得到这些元素。单击回调。如果我运行if$listInputs.attr'name'==单击{alertthis.nodeName$this.children.attr'checked','true'.parent.removeClass'selected';}我在节点名上没有定义-所以我需要找到一种方法使其与条件语句相关:/在整个复杂函数中都需要这样做的情况下,避免出现问题的最佳方法是将变量设置为var u this=$this;谢谢我一直在通过各种方式来尝试解决这个问题,完全没有想到通过点击目标作为一个变量。谢谢@user499846,您可以将元素传递给函数,但也可以在下面看到我的答案。您可以直接将此绑定到您想要的内容。
$('#healthCheckAge li').click( li_click );