最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is there a shorthand for document.write in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

in .NET you have <%= or <%: in PHP it's echo, but does JavaScript have a shorthand for document.write()?

Thanks

Mark

in .NET you have <%= or <%: in PHP it's echo, but does JavaScript have a shorthand for document.write()?

Thanks

Mark

Share Improve this question asked Apr 27, 2011 at 10:19 Mark SandmanMark Sandman 3,33312 gold badges42 silver badges61 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

No, it doesn't.

You can always:

function x (foo) { document.write(foo); } 
/* Where x is an unhelpfully short and uninformative function name */

Generally speaking, document.write should be avoided anyway. It is only useful during initial document generation and does nothing to handle special characters.

Yes, more than one.

But "with" is considered harmful because if you make mistake to call a property that is not set you can change the value of another property or create a new global variable with that property ( more info here )

example

var d = document;
d.write('text');

with (document){
    write('text');
}

The innerHTML property is a useful one for HTML elements. You can use that rather than document.write.

<p id="paragraph1"></p>

<script type="text/javascript">
var elem = document.getElementById("paragraph1");
elem.innerHTML = "This is my paragraph.";
</script>

That allows you to have a lot more control over what you are outputting to the page. You can make that a bit easier to digest by wrapping it in a function - once you've declared the function once, you can reuse it as many times as you like:

<script type="text/javascript">
function wr(a,b) {
var elem = document.getElementById(a);
elem.innerHTML = b;
}
</script>

Very simple example, should be refined etc.

发布评论

评论列表(0)

  1. 暂无评论