开发者

How do I reuse HTML User Interface elements?

I have the following HTML:

<div id="addFieldUI" style="display: none">
<div>
    Field Name:
    <input type="text" />
</div>
<div>
    Field Value
</div>
<div>
    Data Type:
    <select>
        <option>Price</option>
    </select>
</div>

I would like to reuse the HTML in at least two other jQ开发者_如何学编程uery modals. If I use $('#otherElem').html($('#addFieldUI').html()) to insert the HTML into an HTML element I have the problem of duplicate elements if I use input ids for the fields. Should I rather use input names? Should I use a 'script' code block instead of a div? How do I create reusable HTML?

EDIT I am aware of jQuery data templates but in this case I just want to reuse HTML within MODAL dialogs. E.g. if I used the same form for creating and editing data.


Something like this, perhaps:

var counter = 0;
$('#otherElem').html(
    $('#addFieldUI')
        .clone()
        .attr('id', 'addFieldUI-' + counter++)
        .html()
);


You can use a class name as a hook, and than before appending to the other div use Js to dynamically add IDs


There is a library called jQuery Templates and you can always give that a go, I used often in ASP.NET MVC, but works everywhere.

in Git you have some demos

example:

<script id="movieTemplate" type="text/x-jquery-tmpl">
    <li>
        <b>${Name}</b> (${ReleaseYear})
    </li>
</script>

<ul id="movieList"></ul>

<script type="text/javascript">

    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

    $( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜