Bre*_*ett 5 javascript variables jquery
我有一些代码使div的背景颜色渐渐消失.代码目前按照我想要的方式工作,但我想用变量替换它的一部分,以便我可以更改它将影响的div.它所影响的div的id为"one",但当我尝试将变量的值设为变量并将变量放在放置的代码中时,它就不再起作用了.有没有不同的方法可以让它发挥作用?这是代码:
var temp2 = "one";
$(document).ready(function () {
$("#temp2").click(function () {
$("#temp2").animate({
"opacity": "0.15"
}, "slow");
});
});
Run Code Online (Sandbox Code Playgroud)
你很亲密......试试这个.
var temp2 = "#one";
$(document).ready(function () {
$(temp2).click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
Run Code Online (Sandbox Code Playgroud)
或者,你可以只使用一个类而忘记变量.
$(document).ready(function () {
$('.animateMe').click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
Run Code Online (Sandbox Code Playgroud)
另外,如果希望在多个元素上运行相同的处理程序,则可以创建"id"的数组
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");
});
});
});
Run Code Online (Sandbox Code Playgroud)