【问题标题】:Change class on click not working?点击更改课程不起作用?
【发布时间】:2016-05-05 21:24:41
【问题描述】:

尝试使用 jQuery 更改项目的类,但我似乎无法使其工作。出于某种原因,什么都没有发生。

代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $("#theSpinner").click(function() {
        $("#theSpinner").toggleClass("spinning");
    });
</script>

<a href="#" id="reload">
    <img src="spinbut.png" style="width:100px;height:100px;" id="theSpinner" class="notspinning">
</a>

我试过了:

$("#theSpinner").click(function() {
    $("#theSpinner").removeClass("notspinning");
    $("#theSpinner").addClass("spinning");
});

还有$("#reload") 而不是$("#theSpinner"),并带有onClick="" 到包含addClass / removeClass 部分的javascript 函数。

我真的不知道问题出在哪里,但是任何绕过这头公牛的方法都会让我很高兴。

【问题讨论】:

  • 作为附加注释,您应该使用this 而不是点击函数内的相同选择器...
  • @DarkAjax 我是!它在原始代码中,我只是变得绝望。不过谢谢!
  • 您的代码运行良好。您希望看到什么?
  • @Gerard 显然我需要确保它已被加载,仅此而已(请参阅下面的答案)。 =)

标签: javascript jquery


【解决方案1】:

尝试将您的 jQuery 代码包装在“文档就绪”块中,以确保在调用您的函数之前已加载 jQuery:

<script>
    // Example of a document ready function
    $(function(){
        // When jQuery has loaded, wire up this function
        $("#theSpinner").click(function() {
            $(this).toggleClass("spinning");
        });
    });
</script>

示例

您可以see a working example of this in action here并在下面演示:

【讨论】:

  • 我认为 OP 想要同时切换 spinningnotspinning
  • 哎呀。像魅力一样工作。你能详细说明为什么我的 jQuery 之前没有加载吗?我的意思是,基本上,我只是将代码从一页移到了模板中。
  • @JohnSmith 您在#theSpinner 出现在页面上之前搜索它,但什么也没找到,因此没有将点击侦听器附加到任何东西。
  • jQuery 正在加载,但是一旦页面加载,您的事件处理程序就会被调用,此时 jQuery 可能还没有“准备好”。将其包装在该函数中将确保 jQuery 已加载并“准备就绪”。
  • 如果你确实想在两个类之间切换,你应该可以使用$(this).toggleClass('spinning notspinning');
【解决方案2】:

给你

<a href="#" id="reload"> <img src="spinbut.png" style="width:100px;height:100px;" id="theSpinner" class="notspinning"> </a> 
<script type="text/javascript">
  $("#theSpinner").click(function() {
    $(this).toggleClass("notspinning spinning");
  });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多