经过长时间的搜索,我没有找到我要找的东西,或者即使我找到了,它对我正在做的事情不起作用,或者我不知道如何正确使用它。在任何情况下,在这件事上我都真的需要你的帮助。
我所做的是通过仅标识具有 ID 的 div 来定义我的 processing
div
那么剩下的就是用jQuery写的。代码很多,所以我会放一个缩短的版本。
HTML
<div id="blue" class='processing'>
<div class="bar"></div>
<div class="text">BLUE</div>
</div>
<div id="red" class='processing'>
<div class="bar"></div>
<div class="text">RED</div>
</div>
<div id="yellow" class='processing'>
<div class="bar"></div>
<div class="text">YELLOW</div>
</div>
jQuery
$(".processing").click(function () {
var $this = $(this);
var ID = $this.attr('id');
switch(ID){
case "blue":
var name = $this.find(".text").text();
var width = 60;
// some other var(s)
break;
case "red":
var name = $this.find(".text").text();
var width = 40;
// some other var(s)
break;
case "yellow":
var name = $this.find(".text").text();
var width = 20;
// some other var(s)
break;
}
$this.find(".text").text("THE " + name);
$this.find(".bar").css("width", width + "%");
// some other complicated coding
});
解释代码的作用
这是简单版本,所有 div(s) 的 html 相同,但 ID 不同,text
div 也不同。单击 div 后,代码将获取 ID,然后将其与 switch
匹配以获得正确的变量,(还有比这更多的变量)。假设点击了 ID 为 blue
的 div,blue
中标有 class bar
的 div,其宽度将变为 60%根据开关
。如果点击了 red
,red
的条形宽度将更改为 40%,依此类推。
所有重要的变量都在 click
函数中。我想要的是...
我想要什么
在单击之前,我希望用户能够将鼠标悬停在栏上,并且在不单击的情况下,父子关系将显示在文本旁边,然后在鼠标离开后消失。
我知道如何使用函数,使用 mouseenter
和 mouseleave
来做到这一点。
问题
问题是...我将不得不使用变量 3 次。对于 mouseenter
、mouseleave
和 click
。我该怎么做,或者我应该如何处理这些变量,以便我能够在这三个函数中使用它们而无需重复它们。
processing
div是一个矩形,
bar
div 是背景,
text
div 是处理栏上的文本。
图片说明:http://i.imgur.com/nFSrvy6.png
1条提醒
在这个例子中,我想在所有函数中使用的 var
是 width
。但是在我的代码中(长版),不仅仅是一个变量。
最佳答案
为什么不在对象中声明所有变量:
var data = {
blue: {
width: 60,
// other variables
},
red: {
width: 40,
// other variables
},
yellow: {
width: 20,
// other variables
}
}
然后您可以在任何需要的地方使用您的数据对象:
var ID = $this.attr('id');
var width = data[ID].width;
关于javascript - jQuery:为三个函数设置 var(s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26290763/