生成列表:具有多个条件的 JavaScript 函数
您不必熟悉 spry 语法,但我正在使用 SPRY(AJAX 小部件)并尝试编写一个函数来处理多个条件。
spry:when="{ds_CurrentRowNumber} == {ds_RowNumber} && {ds_RowNumber} < 4"
我想把它变成一个函数,每 4 个 li 标签在同一个 div 中生成一个新的 ul 标签,例如:
<ul spry:repeatchildren="ds1">
<li spry:if="{ds_RowID} < 4 ">{item}</li>
</ul>
<ul spry:repeatchildren="ds1">
<li spry:if="{ds_RowID} > 4 && {ds_RowID} < 9 ">{item}</li>
</ul>
这个函数会是什么样子? 非常感谢任何帮助。
You don't have to be familiar with spry syntax but I'm using SPRY (AJAX widget) and trying to write a function to handle multiple conditions.
spry:when="{ds_CurrentRowNumber} == {ds_RowNumber} && {ds_RowNumber} < 4"
I'd like to turn this into a function that generates a new ul tag in the same div every 4 li tags like:
<ul spry:repeatchildren="ds1">
<li spry:if="{ds_RowID} < 4 ">{item}</li>
</ul>
<ul spry:repeatchildren="ds1">
<li spry:if="{ds_RowID} > 4 && {ds_RowID} < 9 ">{item}</li>
</ul>
What would this function look like? Any is help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这通常是使用模运算符(Javascript 中的百分号 - %)完成的。
模数返回“除法后的余数”,它可以准确地告诉您何时到达新的“行”。
所以(根本不知道 Spry)这样的东西: {ds_RowID} % 4 = 0 应该告诉你当你在一个新行时 - 例如第 4 行的模数返回零的 4 % 4 (4 除以 4 有余数为零)。 5 % 4 的模数将为“1”,依此类推。
因此,基本上,当模数为零时,您将进行特殊处理(结束前一个列表 - 如果存在)并开始一个新的处理。
一些伪代码:
itemsPerRow = 4
开始第一行(
)
Loop over all items
Display current item (
)
if currentRow modulus itemsPerRow is zero
OR
if currentRow is the Last
End the row (
)
if currentRow < totalRows - itemsPerRow
There's at least one more row to go, start the next row ()
end if
end if
End Loop
如果您的索引以零而不是一开头,则可能需要对此进行一些更改,但我希望您明白这一点。
This is normally done with the Modulus operator (the percentage sign - % - in Javascript).
Modulus returns the "remainder after division" which can tell you exactly when you've hit a new "row".
So (not knowing Spry at all) something like this: {ds_RowID} % 4 = 0 should tell you when you're at a new row - for example the modulus of row 4 returns 4 % 4 of zero (4 divided into 4 has a remainder of zero). The modulus of 5 % 4 would be "1" and so forth.
So, basically, when the modulus is zero you'd do your special processing (ending the previous list - if one exists) and starting a new one.
Some psuedo code:
itemsPerRow = 4
Start the first row (
)
Loop over all items
Display current item (
)
if currentRow modulus itemsPerRow is zero
OR
if currentRow is the Last
End the row (
)
if currentRow < totalRows - itemsPerRow
There's at least one more row to go, start the next row ()
end if
end if
End Loop
This might need to be changed a bit if your index starts with zero rather than one, but I hope you get the idea.