我是一名学习者,所以我仍然需要经验,并且我有很多问题,但今天我只有一个关于悬停功能的问题。
是否可以将第一个悬停函数中的变量信息发送到第二个悬停函数中?我想你不需要更多信息。只是更改标签中 src 的一部分。
希望你能理解我。 =)
这是示例
http://jsbin.com/eporib/edit#javascript,html,live
现在看起来怎么样!
box.hover(function(){
var $this = $(this),
oldImg = $this.find('img').attr('src'),
slicedOldImg = oldImg.slice(0,-5),
newImg = slicedOldImg+num6;
$this.find('img').attr('src', newImg);
$('#hello').append('IN '+newImg);
}, function() {
var $this = $(this),
oldImg = $this.find('img').attr('src'),
slicedOldImg = oldImg.slice(0,-5),
newImg = slicedOldImg+num1;
$this.find('img').attr('src', newImg);
$('#hello').append('OUT '+newImg+ '<br />');
}); /*end Hover*/
以及我想要的方式
box.hover(function(){
var $this = $(this),
oldImg = $this.find('img').attr('src'),
slicedOldImg = oldImg.slice(0,-5),
newImg = slicedOldImg+num6;
$this.find('img').attr('src', newImg);
$('#hello').append('IN '+newImg);
}, function() {
$this.find('img').attr('src', oldImg);
//look here, the oldImg is in the first function.
// and i want it use it in the second too.
$('#hello').append('OUT '+newImg+ '<br />');
}); /*end Hover*/
最佳答案
是的,至少有两种方法可以做到这一点:
1。使用闭包
将整个内容包装在一个闭包中,并在该闭包中使用一个变量:
(function() {
var oldImg;
box.hover(function(){
var $this = $(this), slicedOldImg newImg;
oldImg = $this.find('img').attr('src'); // Setting it
slicedOldImg = oldImg.slice(0,-5);
newImg = slicedOldImg+num6;
$this.find('img').attr('src', newImg);
$('#hello').append('IN '+newImg);
}, function() {
// Missing `var $this = $(this);` here?
if (oldImg) {
// Use it
$this.find('img').attr('src', oldImg);
// and clear it
oldImg = undefined;
}
$('#hello').append('OUT '+newImg+ '<br />');
} ); /*end Hover*/
})();
在该示例中,我们使用立即为闭包执行的匿名包装函数,但您很可能已经在闭包(函数)中执行此代码,因此您可能不需要添加该包装器。 (如果“闭包”这个词对您来说很陌生,请不要担心,closures are not complicated。)
2。使用数据
或者,您可以使用data
来存储元素的信息:
box.hover(function(){
var $this = $(this),
oldImg = $this.find('img').attr('src'),
slicedOldImg = oldImg.slice(0,-5),
newImg = slicedOldImg+num6;
$this.data("oldImg", oldImg);
$this.find('img').attr('src', newImg);
$('#hello').append('IN '+newImg);
}, function() {
// Missing `var $this = $(this);` here?
var oldImg = $this.data("oldImg");
if (oldImg) {
$this.find('img').attr('src', oldImg);
$('#hello').append('OUT '+newImg+ '<br />');
}
} ); /*end Hover*/
关于jquery 代码改进。悬停函数,我尝试检索有关第一个函数中的值的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8849815/