将元素分配给变量

时间:2014-10-29 23:05:45

标签: jquery

我正在努力为变量分配一个元素 - 我在这里错过了这个情节吗?

animationupgrades = [{
    animation: "height",
    target: $('#element'),
    effect: 33,
    finished: 23
}];

var thisIndex = 0; //as an example

var aniAttribute = animationupgrades[thisIndex].animation;
var target = animationupgrades[thisIndex].target;
var effect = animationupgrades[thisIndex].effect;
var finished = animationupgrades[thisIndex].finished;

$(target).on('mouseover', function() {
    $(this).stop().animate({
        aniAttribute : effect
    },500);
    console.log("errr");
}).on('mouseout', function() {
    $(this).stop().animate({
        aniAttribute : finished
    },500);
});

编辑:对不起,它实际上是一个对象 - 我错了!为什么所有的downvotes?

编辑2:小提琴! http://jsfiddle.net/28wone62/

2 个答案:

答案 0 :(得分:1)

对象定义

var aniAttribute = "height";
{ aniAttribute : "literal" }

定义名为“aniAttribute”的属性,而不是名为“height”的属性

这是一个可行的解决方案。

animationupgrades = [{
    animation: "height",
    target: $('#element'),
    effect: 33,
    finished: 23
}];

var thisIndex = 0; //as an example

var attr = animationupgrades[thisIndex].animation;
var target = animationupgrades[thisIndex].target;
var effect = animationupgrades[thisIndex].effect;
var finished = animationupgrades[thisIndex].finished;

$(target).on('mouseover', function() {
    console.log("a", attr, target, effect + "px", finished);
    var obj = {};
    obj[attr] = effect + "px";
    $(this).stop().animate(obj, 500);
}).on('mouseout', function() {
    var obj = {};
    obj[attr] = finished + "px";
    $(this).stop().animate(obj,500);
});
.red {
  background: red;  
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="red" id="element">
  asdasdasdasd
</div>

答案 1 :(得分:0)

试试这个:

   animationupgrades = [ {
        animation: "height",
        target: $('#element'),
        effect: 33,
        finished: 23 }
   ];