开发者

user control using javascript

I want to make a kind of user control using javascript.

<div id="myDiv">
  <input type="text" id="myText" />
</div>
开发者_JAVA百科

I want to insert this div in my HTML markup, wherever I required. Purpose is to make it reusable at various places in my HTML and maintain a single point of change, if I need to change the control in future. I would like to have a javascript function for it. I need best possible ways to do it maybe using jquery.


I think what you're after is a decent candidate for the new jQuery templates. You can find a tutorial here, for example:

<script id="myTemplate" type="text/x-jquery-tmpl">
  <div id="myDiv${ID}">
    <input type="text" id="myText${ID}" />
  </div>  
</script>

Then when using it, it would look like this:

$("#myTemplate").tmpl([{ID: 1}]).appendTo("#something");

This is just an example, your IDs should be unique and not duplicated anywhere in the page, even as a result of appending them through JavaScript. If you want a template to reuse this is a pretty flexible way to do, more so if you're passing data as well, for example:

<script id="myTemplate" type="text/x-jquery-tmpl">
  <div id="myDiv${ID}">
    <input type="text" id="myText${ID}" value="${Val}" />
  </div>  
</script>

And just add that property in:

$("#myTemplate").tmpl([{ID: 1, Val: "Test"}]).appendTo("#something");

Or you could pass an array to .tmpl() to make many of these at once, as the result of a JSON response, etc. Also based on your comment, yes you can also get the template from as an external file, like this.


If I get it right, you need the clone() function Clone()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜