将 var 设置为单击按钮值并使用 var

setting var as clicked button value and using var

本文关键字:var 单击 设置 按钮      更新时间:2023-09-26

我用点击按钮的值设置 var x 的值。然后我想使用 var x 作为我的 jquery 动画代码中的值。

var x = $('input').click(function() {
    $(this).val();
});
$("li").click(function() {
    $(this)
        .stop()
        .animate(
            {height:'150px'},
            {queue:false, duration:600, easing: x }
        );
});
$("li").mouseout(function() {  
    $(this)
        .stop()
        .animate(
            {height:'50px'},
            {queue:false, duration:600, easing: x });
});​

我做错了什么?演示 : http://jsfiddle.net/EnigmaMaster/z9dXA/7/

demo jsFiddle

var x = '';    // define your var (make it re-usable inside functions)
$('input').click(function() {
   x = $(this).val();   // set your var'x' value for use.
});
$("li").click(function() {   
    $(this).stop().animate({height:150},{queue:false, duration:600, easing: x });
});
    
$("li").mouseout(function(){  
    $(this).stop().animate({height:50},{queue:false, duration:600, easing: x });
});

单击是异步的。这样做:

var x;
$('input').click(function() {
    x = $(this).val();
});

见小提琴:http://jsfiddle.net/z9dXA/8/

这只有在顺便说一下在 li 之前单击输入时才有效,否则 x 将没有值。也许提供一个默认值,如下所示:

var x = 'swing';
$('input').click(function() {
    x = $(this).val();
});

您当前设置x等于$("input")返回的jQuery对象。.click()方法设置一个稍后将调用的单击处理程序(当单击发生时(,因此它不会在单击时返回值 - 它返回与$("input")相同的 jQuery 对象,以便您可以将多个 jQuery 方法链接在一起。这就是为什么你的alert(y)显示[object Object].

尝试将第一位更改为以下内容:

var x = "linear";  // give x a default value
$('input').click(function() {
    x = $(this).val();  // store the type of easing to be used
});

那么你实际上不需要y变量,你可以直接使用 x

$("li").click(function() {
    $(this).stop().animate({ height: '150px' }, {
        queue: false,
        duration: 600,
        easing: x
    });
});
$("li").mouseout(function() {
    $(this).stop().animate({ height: '50px'}, {
        queue: false,
        duration: 600,
        easing: x
    });
});​

更新的演示:http://jsfiddle.net/z9dXA/9/