这是我的小提琴:http://jsfiddle.net/wr1k02ym/3/
忽略那里的文本框,文本框应该仅在您双击文本时才显示,但由于某种原因它显示在小提琴中(它在我的主程序中工作正常,所以我想这是一个 CSS 问题。
基本上,我正在显示一些文本,如果文本在这样的跨度中:
<span class="output" title="lalalalalblas asdl sda lasdl asdb">lalalalalblas asdl...</span>
如果文本太长,它只显示部分文本,然后在鼠标悬停上时显示标题中的全文。
在我的Javascript中,我像这样进行切换:
var tip;
var orig;
var switched = 0;
$('.output').hover(
function () {
tip = $(this).attr('title');
orig = $(this).text();
if (tip != orig) {
$(this).fadeOut(function () {
$(this).text(tip).fadeIn();
switched = 1;
});
}
},
function () {
if (switched == 1) {
$(this).fadeOut(function () {
$(this).text(orig).fadeIn();
switched = 0;
orig = "";
});
}
});
});
如您所见,我的JS非常简单,但是当您将鼠标从下面的文本移动到上面的文本上时,问题出现了(去我的小提琴进行测试)......然后由于某种原因,这个变量取另一个变量的值。
如何让它工作,使其不采用其他变量文本?
您的 tip
、 orig
和 switched
变量在处理程序函数之间共享,因此在所有元素之间共享。您可以像这样为每个元素创建变量:
$('.output').each(function() {
var tip;
var orig;
var switched = 0;
$(this).hover(function () {
tip = $(this).attr('title');
orig = $(this).text();
if (tip != orig) {
$(this).fadeOut(function () {
$(this).text(tip).fadeIn();
switched = 1;
});
}
}, function () {
if (switched == 1) {
$(this).fadeOut(function () {
$(this).text(orig).fadeIn();
switched = 0;
orig = "";
});
}
});
});
现在,每个输出元素都有一个tip
、orig
和switched
。
小提琴:http://jsfiddle.net/wr1k02ym/4/