开发者

Using jQuery to echo text

Is it possible to use jQuery to echo text in place of a script tag? More precisely, is there a way to accomplish

<script type="text/javascript">
    document.write("foo");
</script>

开发者_开发知识库... without the use of document.write? I am not happy about using document.write after reading this.

I am aware that I could alternatively do this:

<span id="container"></span>
<script type="text/javascript">
    $("#container").text("foo");
</script>

However, I'm interested to see if there's a way to do it without using a container element, preferably using jQuery.

Thanks in advance!


If you come up with a jQuery way of doing document.write(), it'll be bad for all the same reasons.

You are better off just using document.write() if that's what you need, or better yet, manipulating an existing element or appending a new element somewhere in the DOM--that's what jQuery is good at.


Yes, and No. For what you want, no.

  1. Can you have it echo text to something without a true container, yes (see: DocumentFragment).

  2. Will it show up in your document... no. This is because it has not been told where it should be placed. The script tags in html do not maintain their position as a parameter directly so you could fudge around to find the last tag and put a TextNode there, however, this can be difficult and buggy.

What you can do instead is the general practice of do not modify the dom until an event such as "document.body.onLoad". This is a common practice, and generally is the way to go for ajax especially.

If none of this is suited for you, use the rare insertBefore(), jquery provides comparable support with .after and .before, on your script element with an id.

<script id="flail">
var flail=document.getElementById("flail");
flail.parentNode.insertBefore(document.createTextNode("TEST"),flail)
</script>

Note: This is generally a bad practice as it can create hanging loads, and encourages the html page to not be coherent without this output. However, like all things, there are cases for it's use.


I suggest you to implement the Micro Template Engine by John Resig, jquery founder.

The full plugin

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function() {
    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
                cache[str] = cache[str] ||
                tmpl(document.getElementById(str).innerHTML) :
                // Generate a reusable function that will serve as a template
                // generator (and which will be cached).
                new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                // Introduce the data as local variables using with(){}
                "with(obj){p.push('" +
                // Convert the template into pure JavaScript
                str
                .replace(/[\r\t\n]/g, " ")
                .split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                .replace(/\t=(.*?)%>/g, "',$1,'")
                .split("\t").join("');")
                .split("%>").join("p.push('")
                .split("\r").join("\\'")
                + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();

Use

IMPORTANT : Break lines only with \

var tpl = '\
    <div id="myTemplate">\
        <%\ var selectorIndex = 0;\ %>\
           <ul>\
                <% if( selectorIndex == 0 ){ %>\
                <li>this is echo text for zero</li>\
                <% } else{ %>\
                <li>this is echo text for something else</li>\
                <% } %>\
           </ul>\
    </div>\
';

$(body).html(tmpl(tpl,{'extraData':'here'}));

More info

http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line

Related questions on stackoverflow

Syntax Error with John Resig's Micro Templating after changing template tags <# {% {{ etc

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜