jquery - 将随机变量传递给 addClass

标签 jquery addclass

只想生成一个随机数,然后将其作为类添加到现有的 div 中。

但是无法让addClass识别该变量。

JS

$(function() {
    $("#button_text").mouseenter(function() {
        var randomNum = Math.Round(Math.random()*3);
        $("#buttons").addClass(randomNum);
    }).mouseleave(function() {
        $("#buttons").removeClass(randomNum)
    });
});

HTML

<div id="buttons">
</div>

非常感谢任何帮助。

<小时/>

感谢您的帮助。

最终解决方案是...

JS

$(function() {
    $("#button_text").mouseenter(function() {
        randomNum = 'rand' + Math.round(Math.random()*2);
        $("#buttons").addClass(randomNum);
    }).mouseleave(function() {
        $("#buttons").removeClass(randomNum)
    });
});

HTML

<div id="buttons">
</div>
<p>Insert intro sentence here.</p>
<div id="button_text">
  <p>Insert text here that will display the random button background when moused over</p>
</div>

CSS

#button_text
{
    display: block;
}
#buttons
{
    width: 200px;
    height: 200px;
    display: block;
    position: absolute;
    top: 145px;
    left: 370px;
    z-index: -999;
}
#buttons.rand0
{
    background: url(/hover_buttons.png) no-repeat;
    background-position: 0 0;
}
#buttons.rand1
{
    background: url(/hover_buttons.png) no-repeat;
    background-position: 0 -230px;
}
#buttons.rand2
{
    background: url(/hover_buttons.png) no-repeat;
    background-position: 0 -440px;
}

最佳答案

这里有几个问题。

  1. 范围 - 调用 mouseout 方法时,变量 randomNum 不存在,因此仅添加您的类。

  2. 即使您将其设置为全局变量,如果您多次使用此代码,也无法解决您的问题(情况可能并非如此,因为您似乎正在使用 ID,但以防万一。 )

  3. 它是 Math.round 而不是 Math.Round

  4. 类不应仅由数字组成

我使用 jQuery 数据 api 来存储随机类名,以便您稍后可以检索它。这是您想要实现的目标的 fiddle :http://jsfiddle.net/jomanlk/339c5/

$("#button_text").mouseenter(function() {
    var randClass = 'randomClass' + Math.round(Math.random() * 3);
    $("#buttons").addClass(randClass);
    $("#buttons").data('randClassValue', randClass);
}).mouseleave(function() {
    var randClass = $("#buttons").data('randClassValue');
    $("#buttons").removeClass(randClass)
});

<p id='button_text'>
    <a id='buttons'>Buttons</a>
</p>

关于jquery - 将随机变量传递给 addClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6502705/

相关文章:

javascript - 如何使用ajax从客户端将文件发送到服务器端而不使用处理程序?

Jquery 带有 else if 语句的外部链接

jQuery : Add class dynamically depending on the browser window resolution

javascript - Jquery addClass 不是持久的

jquery - 使用 jquery 将Class添加到<a>

javascript - 在 addClass/removeClass 中使用多个变量

javascript - 未捕获的类型错误 - 无法读取 null 的属性 'owlcarousel'

jquery - 将网站背景的 youtube 视频静音

javascript - "Click"事件由于 "blur"而未被触发

jquery - Html Agility Pack 无法删除节点