如何使用JavaScript / jQuery动态填充多个div?

时间:2014-06-29 15:10:39

标签: javascript jquery

我提前道歉,我不允许发布图片,直到我有10个声望。所以,我希望我的描述足以让我了解我的想法。

所以,说我有三列; a,b和c。当只有a,b和c中存在太多内容时,我想要制作新的离屏列,d,e和f。 - 这一直持续到使用所有内容为止。

所以,我当前的设置有所有内容的“隐藏文本”div播放主机,然后我有一个JavaScript函数或jQuery函数来动态填充每个div,并在需要的地方创建div用按钮然后到达它创建的新div。

确定填充内容的方式只是抓取内容并将其放入a列。当内容到达屏幕底部时,列a已满。然后它抓取其余内容并将其放入b,直到b已满,依此类推,直到使用了所有可用内容。

我真的希望我足够清楚,我不知道是否有人甚至会远远地理解我想说的话......任何帮助都非常感谢!

以下是HTML结构的代码片段,也许它可以帮助别人理解我的意思......再次感谢大家!

<div id="parent-div">
   <div class="a"></div>
   <div class="b"></div>
   <div class="c"></div>
</div>
<div id="hidden-text">
   This is the content I would like to have displayed across the three divs above.
</div>

这是我到目前为止的一些JS,我宁愿坚持从这里开始:

function Populate(){
//paragraph is equal to all of the content in the hidden-text div
var paragraph = document.getElementById('hidden-text').innerHTML;
var newParagraph = "";

//the variable div would play host to the names of each of the divs in the HTML
var div = "";
//words stores each character of paragraph and passes them into the new paragraph
var words = "";

for (words in paragraph)
{
    newParagraph += paragraph[words];
}
//the column with the name equal to the value of the div variable gets populated by the value of newParagraph
document.getElementByClassName(div).innerHTML = newParagraph;}

1 个答案:

答案 0 :(得分:0)

我认为它应该是这样的:

var divs = ['a', 'b', 'c'];
var word_limit = 50;
var paragraph_words = paragraph.split(' ');
for (var i = 0, div_index = 0; i < paragraph_words.length && div_index < divs.length; i++) {
    newParagraph += ' ' + paragraph_words[i];
    if (i > 0 && i % word_limit == 0) {
        document.getElementsByClassName(divs[div_index])[0].innerHTML = newParagraph;
        div_index++;
        newParagraph = '';
    }
}
if (newParagraph) { // If we didn't fill up the last DIV
    document.getElementsByClassName(divs[div_index])[0].innerHTML = newParagraph;
}
相关问题