1

I want to generate dynamically a few elements (not known in advance how many) and glue them together and essentially extend a div, say with id "myDiv". For demonstration purposes, say that a client receives a message to generate a list of three buttons on the fly by extending the div.

I am stuck though, because I generate the list like this

var temp = "<ul>";
for (i = 0; i < someTimes; i++) {
    temp += "<li>some text <div id=\"button" + i + "\"></div></li>";
}
temp += "</ul>";

then do

document.getElementById('myDiv').innerHTML = html;

and in order to generate each button my initial intention was to then do this in order to append each button to the appropriate div that was generated on the fly in the while loop. But this thing does not work. Perhaps there are a few things here for a newbie like me;

  1. Is there a Javascript example that I could use inside the for loop in order generate the buttons dynamically, give them the id that I want and delegate them?
  2. Should I convert the first part from Javascript to jQuery and then do both things simultaneously with jQuery? How (in this example)?
  3. Is there a good reference for these things?

Thank you in advance for your time. I do not expect answers to all three questions but I would like to get an answer on how to achieve this mini goal as a guideline on how to continue my work.

4

3 回答 3

2

好吧,我可以向您推荐一个用于模板的库插件。

但我很确定它可以用几行代码来完成(穷人的模板引擎(crockford):

if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

那么它将如何工作:

这将是您的结构:(从技术上讲,您可以(并且应该)将其放在文本/模板部分下)

var t= '<tr data-symbol="{Symbol}"><td>{Symbol}</td><td>{Price}</td><td>{DayOpen}</td></tr>';

这是绑定部分:

t.supplant({Symbol:'s',Price:2,DayOpen:3})

活生生的例子

于 2013-09-30T13:09:45.240 回答
1

这就是使用 Jquery 完成的方式

var $ul = $('<ul></ul>');
for (i = 0; i < someTimes; i++) {
    $ul.appent("<li>some text <div id='button" + i + "'></div></li>");
}
$('#myDiv').append($ul);
于 2013-09-30T13:14:45.840 回答
0

您可以appendToJQuery. 语法是:

$(content).appendTo(selector)

jquery 文档页面上的示例是:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

$( "<p>Test</p>" ).appendTo( ".inner" );

编辑:根据评论..

<div class="placeholder"></div>

$( "your generated html" ).appendTo($(".placeholder"));
于 2013-09-30T13:18:33.060 回答