2010-02-10 120 views
0

对于所有jQuery专家,我可以使用您的帮助指出我的部分可能是一个愚蠢的错误。当用户点击一个带有热点类的div时,我试图交换类onclick。下面的代码在我第一次点击时交换了课程,而不是第二次和以后的课程。此外,如果有更清晰的方式来完成这个请让我知道。在jQuery中更改类仅在第一次点击时才起作用

在此先感谢您的专业知识。

的jQuery:

$('.hotspot').click(function() { 
    if($(this).parent().attr("class") == 'checked'){ 
     $(this).parent().removeClass('checked').addClass('unchecked'); 
    } 
    if($(this).parent().attr("class") == 'unchecked'){ 
     $(this).parent().removeClass('unchecked').addClass('checked'); 
    } 
}); 

标记:

<ul id="prettyCheck"> 
    <li class="checked"> 
      <div class="hotspot"></div> 
      <div class="desc"><div class="descPad">Some text</div></div> 
    </li> 
    <li class="unchecked"> 
      <div class="hotspot"></div> 
      <div class="desc"><div class="descPad">Some text</div></div> 
    </li> 
</ul> 

回答

0

试试这个

$('.hotspot').toggle(function() { 
     $(this).parent().removeClass('checked'); 
     $(this).parent().addClass('unchecked'); 
     // do more here... 
    }, 
    function(){ 
     $(this).parent().removeClass('unchecked'); 
     $(this).parent().addClass('checked'); 
     // do more here... 
}); 

$('.hotspot').click(function() { 
     $(this).parent().toggleClass('checked'); 
     $('checkbox selector').attr('checked', $(this).parent().hasClass('checked')); 
     // do more here... 
    }); 
+0

谢谢!肯定会越来越近,切换工作得很好,我发现我可以根据需要继续添加,唯一的问题是,当班级默认为未选中时,我必须在班级切换之前点击两次。我曾尝试交换功能,但只有在检查时导致相同的情况才是默认设置。 – Sheldon 2010-02-10 06:00:48

+0

尝试我的更新以上... – Reigel 2010-02-10 06:01:51

+0

你的更新是完美的切换类,我仍然搞清楚如何做切换后,我需要的条件事物,即。除了复选框以外,还显示/隐藏了其他div。 – Sheldon 2010-02-10 06:14:08

0

你试过没有chaning?

$('.hotspot').click(function() { 
    if($(this).parent().attr("class") == 'checked'){ 
     $(this).parent().removeClass('checked'); 
     $(this).parent().addClass('unchecked'); 
    } 
    if($(this).parent().attr("class") == 'unchecked'){ 
     $(this).parent().removeClass('unchecked'); 
     $(this).parent().addClass('checked'); 
    } 
}); 
+0

你敢打赌,和链式单行相同的结果,第一次工作,但不是以后的时间。 – Sheldon 2010-02-10 05:39:56

0

我认为问题是,如果类已经被选中,那么第一if语句将取消它,那么接下来if将重新检查它。尝试将第二个if更改为else if,然后查看是否可以为您解决问题。我这样做了,也做了什么sberry2A建议通过替换.attr('class') == 'checked'.hasClass('checked'),它是为我工作。

编辑:至于为什么你只能用你的原代码,一旦切换每个元素,这是因为如果类的名字都是一模一样“检查”(和同样为.hasClass('unchecked')的测试.hasClass('checked')只会是真实的和类名“unchecked”)。 jQuery的addClass()函数会为您提供的类提供一个空间,所以如果您告诉它添加“checked”类,它会将字符串“checked”添加到类名。因此,以类名“checked”开头的元素将被修改为使类名称“未选中”,并且不再与您的if语句中的任何一个相匹配,从而防止它再次触发。这就是为什么sberry2A建议使用hasClass(),因为如果元素的类名包含传递它的类,即使类名中有额外的空间或其他类,它也会返回true。

0

Got it! 除了Reigels代码之外,我还可以将ID添加到每个热点,并将其用于其他onclick函数来执行我需要的任何操作。

感谢您的帮助!

相关问题