Javascript 使用 jQuery 回显文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2562244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:55:55  来源:igfitidea点击:

Using jQuery to echo text

javascriptjquery

提问by susmits

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

是否可以使用 jQuery 来回显文本来代替脚本标记?更准确地说,有没有办法实现

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

... without the use of document.write? I am not happy about using document.writeafter reading this.

...不使用document.write? document.write读完这篇后我对使用不满意。

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.

但是,我很想知道是否有办法在不使用容器元素的情况下做到这一点,最好使用 jQuery。

Thanks in advance!

提前致谢!

采纳答案by bmeck

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.

  1. 你能让它在没有真正容器的情况下回显文本吗?是的(参见:DocumentFragment)。

  2. 它会出现在您的文档中吗...不。这是因为它没有被告知应该放置在哪里。html 中的脚本标签不直接作为参数保持它们的位置,因此您可以四处寻找最后一个标签并将 TextNode 放在那里,但是,这可能很困难且有问题。

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.

你可以做的是一般的做法是在诸如“document.body.onLoad”之类的事件发生之前不要修改dom。这是一种常见的做法,尤其是 ajax 的做法。

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.

如果这些都不适合您,请使用罕见的 insertBefore(),jquery 在具有 id 的脚本元素上提供与 .after 和 .before 类似的支持。

<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.

注意:这通常是一种不好的做法,因为它会创建悬挂负载,并鼓励 html 页面在没有此输出的情况下不连贯。但是,像所有事物一样,它也有使用的情况。

回答by Michael Haren

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

如果你想出一种 jQuery 的方式来做document.write(),那么出于同样的原因,它会很糟糕。

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.

document.write()如果这是您的需要,您最好只使用它,或者更好的是,操作现有元素或在 DOM 中的某处附加一个新元素——这正是 jQuery 擅长的。

回答by RafaSashi

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

我建议您实现jquery 创始人John Resig的微模板引擎。

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, "\r")
                .replace(/\t=(.*?)%>/g, "',,'")
                .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

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

Related questions on stackoverflow

stackoverflow的相关问题

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

更改模板标签后,John Resig 的微模板出现语法错误 <# {% {{ 等