我将var x的值设置为单击按钮的值。然后我想在我的jquery动画代码中使用var x作为值。
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/
答案 0 :(得分:4)
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 });
});
答案 1 :(得分:2)
点击是异步的。这样做:
var x;
$('input').click(function() {
x = $(this).val();
});
请参阅小提琴:http://jsfiddle.net/z9dXA/8/
只有在顺便说一下li之前点击输入时才会有效,否则x将没有值。也许提供一个默认值,如:
var x = 'swing';
$('input').click(function() {
x = $(this).val();
});
答案 2 :(得分:1)
您当前正在设置x
等于$("input")
返回的jQuery对象。 .click()
方法设置一个点击处理程序,稍后将调用 (当点击发生时),因此它不会返回点击时的值 - 它返回相同的值jQuery对象为$("input")
,因此您可以将多个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
});
});