基本的Jquery无法正常工作-请进行健全性检查 [英] Basic Jquery not working properly - sanity check please

查看:112
本文介绍了基本的Jquery无法正常工作-请进行健全性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对标签元素使用以下Jquery,以根据其当前状态添加或删除类.

I am using the following Jquery on label elements to add or remove a class depending on it's current state.

$('label').click(function(){
if ($(this).hasClass('selected')){
    //alert('its classy');
    $(this).removeClass('selected')
} else {
    $(this).addClass('selected');
    //alert('its NOT classy');
    }
});

就我而言,它应该可以工作!但是,在Firefox中,这需要双击,而在Chrome中,则根本无法使用.

As far as I am concerned it should work! However in Firefox this requires a double-click and in Chrome it doesn't work at all.

当前,这是页面上唯一的任何一种Javascript,因此不会被任何插件或类似的东西破坏.

Currently this is the only Javascript of any kind on the page so it's not being broken by any plugins or anything like that.

元素的相关html如下所示:-

The relevant html of the element looks like this:-

<label class="">Filter item<input type="checkbox" /></label>

谢谢.

推荐答案

我不知道为什么会这样,但是您可以通过将input移到label之外来解决此问题:

I don't know why this is the case, but you can fix the problem by moving the input outside of the label:

<label for="yourCheckbox">Filter item</label>
<input type="checkbox" id="yourCheckbox" />

这是一个工作示例.请注意,该示例使用@Matt在问题注释中建议的toggleClass.我已经在Chrome和Firefox中都尝试过了,而且看起来工作正常.

Here's a working example. Note that the example uses toggleClass as suggested by @Matt in the comment on your question. I've tried it in both Chrome and Firefox and it seems to work fine.

这篇关于基本的Jquery无法正常工作-请进行健全性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆