Jquery 将类添加到单选项父级的最佳方法是删除和添加类

Jquery 将类添加到单选项父级的最佳方法是删除和添加类,jquery,selector,Jquery,Selector,关于jQuery和改进代码的快速问题 基本上,在选择单选按钮后,我将向父容器添加一个select类,在本例中是列表项。更改时从以前选择的项目中删除select类 我不禁觉得有更好的方法来压缩和清理下面的代码 $('#fubar input[name=game]').change(function(){ $('.selected').removeClass('selected'); $(this).parent('li').addClass('selected'); }) 谢谢你

关于jQuery和改进代码的快速问题

基本上,在选择单选按钮后,我将向父容器添加一个select类,在本例中是列表项。更改时从以前选择的项目中删除select类

我不禁觉得有更好的方法来压缩和清理下面的代码

$('#fubar input[name=game]').change(function(){
    $('.selected').removeClass('selected');
    $(this).parent('li').addClass('selected');
})
谢谢你的帮助:非常感谢

$('#fubar input[name=game]').change(function(){
    $this = $(this);
    $this.closest('ul').find($('.selected')).removeClass('selected');
    $this.closest('li').addClass('selected');
})
您唯一可以更改的是.parent to.nexist-但您的解决方案看起来还可以,

尝试使用nexist并查找:

发件人:

//快速:$container div.robotarm; //超快:$ container.find div.robotarm


您还可以尝试为要更改的两个元素切换类,这将更短:

$(this).closest('li').add('.selected').toggleClass('selected');
一种方法:

$(document).ready(function() {
  // this detects the change event as it propagates through to the
  // <li> element:
  $('li').on('change', function() {
    // adds the 'selected' class-name to the <li> that
    // holds the changed <input> (the change event is 
    // fired only on checking the <input>):
    $(this).addClass('selected')
    // selects the siblings of the <li>:
    .siblings()
    // removes the 'selected' class-name from those siblings:
    .removeClass('selected');
  });
});
李{ 边框:1px000; 保证金:0.5em0; 列表样式类型:无; } 李先生当选{ 边框颜色:f00; } 一 二 三 四
我一周写一次这样的代码。简单一点就好了,您可以通过提供一个简单的示例,在牺牲代码易读性的情况下进行一些非常小的性能改进,但通常就是这样做的。不知道人们为什么会提供“最近的”,除非以后如果您的结构发生变化,它可能会为您节省一些代码。@如果li不是您输入的直接父对象,则使用JohnGreen Nestest。如果你有。。。然后父母就不再工作了,或者你将不得不做父母。父母。父母…,但最接近的人会这样做。@PierreGranger-就像我说的。。如果他的结构发生变化,它可能会在以后为他保存一些代码,因为现在看来这并不是一个问题。我只是想说,这与代码是否紧凑/干净的问题无关。你知道其中的区别,但可能不是@karen_west,所以最好解释一下为什么有些人更喜欢cloest;只需$this.closest'ul'。查找'li'。删除类'selected',以确保它不会删除其他ul中其他li上的所选内容。而不是删除类的第一行。是否在页面中的任意位置删除选中了.wut的任何元素上的类?这是做什么的|$这是最近的'li'.add'.selected'-jQuery包装器,已单击并当前选中。然后为这两个类切换类“selected”,如果存在则删除,如果不存在则添加。同级。。。如此经典,从未想过:|我没有跨浏览器测试过它,但更改事件在Windows7上的Chrome35.x中传播。非常详细的答案。我讨厌第一个例子把所有的LIs都拿出来,但我可以接受第二个。不过,我可能会在变更闭包内部执行最接近的操作:$this.closest'li'.addClass'selected'.sides.removeClass'selected';。最近的过滤器不会被缓存,但您不必等待气泡,也不必为二阶过滤器支付加载成本。最后,这种微优化甚至可以节省2ms。
$(document).ready(function() {
  // this detects the change event as it propagates through to the
  // <li> element:
  $('li').on('change', function() {
    // adds the 'selected' class-name to the <li> that
    // holds the changed <input> (the change event is 
    // fired only on checking the <input>):
    $(this).addClass('selected')
    // selects the siblings of the <li>:
    .siblings()
    // removes the 'selected' class-name from those siblings:
    .removeClass('selected');
  });
});