如何在函数中返回变量值?
var myString = "px";
var myMethod = function(){
if(myString == 'percent') {
return '%';
} else {
return myString; // should return 'px'
}
$('div').css('width','200'+myMethod()); //not working
因为我遇到了这个问题:
var sCalc = this.className.split('-')[4];
var fnCalc = function(){
if(sCalc == 'plus'){
return '+';
} else if(sCalc == 'minus'){
return '-';
} else if(sCalc == 'multiply'){
return '*';
} else if(sCalc == 'divide'){
retutn '/';
} else{
return '+';
} /*bugging me this too much*/
};
我在控制台中没有看到任何错误?
答案 0 :(得分:4)
你错过了大括号来结束你的功能。
var myString = "px";
var myMethod = function() {
if (myString == 'percent') {
return '%';
} else {
return myString; // should return 'px'
}
};
$('div').css('width','200'+myMethod()); //not working
更新了JSFiddle
答案 1 :(得分:0)
<script>
var myString = "px";
var myMethod = function(){
if(myString=='percent'){
return '%';
} else {
alert(myString); // should return 'px'
}
}
$('div').css('width','200'+myMethod());
</script>
<div style="background: red; position: absolute;">test</div>