admin管理员组文章数量:1424942
I have some code that makes the background color of a div fade. The code is currently working the way I want it to, but I would like to replace part of it with a variable so I can change which div(s) it will affect. The div that it is affecting has an id of "one", but when I try to make that the value of a variable and stick the variable in the code in it's placed, it doesn't work anymore. Is there a different way I can do this to make it work? Here is the code:
var temp2 = "one";
$(document).ready(function () {
$("#temp2").click(function () {
$("#temp2").animate({
"opacity": "0.15"
}, "slow");
});
});
I have some code that makes the background color of a div fade. The code is currently working the way I want it to, but I would like to replace part of it with a variable so I can change which div(s) it will affect. The div that it is affecting has an id of "one", but when I try to make that the value of a variable and stick the variable in the code in it's placed, it doesn't work anymore. Is there a different way I can do this to make it work? Here is the code:
var temp2 = "one";
$(document).ready(function () {
$("#temp2").click(function () {
$("#temp2").animate({
"opacity": "0.15"
}, "slow");
});
});
Share
Improve this question
edited Apr 27, 2013 at 2:42
Derek 朕會功夫
94.5k45 gold badges198 silver badges253 bronze badges
asked Apr 27, 2013 at 2:20
BryanBryan
3,00914 gold badges67 silver badges105 bronze badges
1
-
1
Remember that
$()
expects a string as an argument (for selectors) and temp2 is a variable name (not a string). – jahroy Commented Apr 27, 2013 at 2:50
1 Answer
Reset to default 7You're close... try this.
var temp2 = "#one";
$(document).ready(function () {
$(temp2).click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
here's a working example
Alternatively, you can just use a class and forget about the variable.
$(document).ready(function () {
$('.animateMe').click(function () {
$(this).animate({
opacity: '0.15'
},
"slow");
});
});
Please see this working example
also, you can create an array of "id's" if you want the same handler to run on multiple elements
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");
});
});
});
here's a working example
本文标签: javascriptjquery variables not workingStack Overflow
版权声明:本文标题:javascript - jquery variables not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745410041a2657422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论