【发布时间】:2016-12-04 23:15:31
【问题描述】:
我正在尝试创建一个函数,每次运行时都会增加其参数。你总是可以手动重写函数,但我将多次运行这个函数,希望能够方便地重用代码。
$("div").each(function() {
function rangeF(firstValue, increment) {
var first = firstValue + "-"; //Set the first value and put a hypen after it
firstValue += increment; //Increment it by the increment
var second = firstValue; //Set the second value
firstValue++; //Increment by one to avoid duplicates
return first + second; //return both values (e.g. 1-2 or x-y)
}
range = rangeF(5 , 10); //5 is the value to start on, 10 + 1 is the increment (need to access both 5 + 10 & 5 + 11)
range2 = rangeF(2, 2); //2 is the value to start on, 2 + 1 is the increment (need to access both 2 + 2 & 2 + 3)
$(this)
.append('<div>' + range + '</div>')
.append('<div>' + range2 + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#1 range: <div></div>
<br />
#2 range: <div></div>
<br />
#3 range: <div></div>
现在,它正在显示:
#1 range:
P 5-15
P 2-4
#2 range:
P 5-15
P 2-4
#3 range:
P 5-15
P 2-4
我想显示:
#1 range:
P 5-15
P 2-4
#2 range:
P 16-26
P 5-7
#3 range:
P 27-37
P 8-10
尽可能以最干净、可重复使用的方式。
提前致谢。
更新抱歉造成混淆,但我的意思是我不想使用重复使用的全局变量来解决...再次感谢您的所有贡献。
【问题讨论】:
-
您当前的功能到底在做什么?你能解释或评论吗?
-
你可以在 $("div").each(function() { 之后放一个变量吗?
-
@Daidon 他确实说过“我想保存全局变量以备不时之需。”
-
@Daidon 当然!只要我不必继续添加变量。
-
@ChrisHappy 好的,回答 commin' up
标签: javascript jquery function