我有一些代码可以使div的背景色变淡。代码目前按照我想要的方式工作,但我想用变量替换它的一部分,以便我可以更改它将影响的div。它所影响的div的id为“one”,但当我尝试将变量的值设为变量并将变量放在放置的代码中时,它就不再起作用了。有没有不同的方法可以让它发挥作用?这是代码:
var temp2 = "one";
$(document).ready(function () {
$("#temp2").click(function () {
$("#temp2").animate({
"opacity": "0.15"
}, "slow");
});
});
答案 0 :(得分:7)
你关闭......试试这个。
var temp2 = "#one";
$(document).ready(function () {
$(temp2).click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
或者,你可以使用一个类而忘记变量。
$(document).ready(function () {
$('.animateMe').click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
Please see this working example
另外,你可以创建一个" id' s"如果你想在多个元素上运行相同的处理程序
var arr = ["one", "two", "three", "four", "five"];
$(document).ready(function () {
// loop through the array
jQuery.each(arr, function () {
// create a local variable
var id = '#' + this;
$(id).click(function () {
$(id).animate({
opacity: '0.15'
},
"slow");
});
});
});