简体   繁体   English

将html分配给javascript变量是一种好习惯吗?

[英]Is assigning html to javascript variable a good practice?

I am a newbie to html/css/javascript and code like this really scares me: 我是html / css / javascript和类似这样的代码的新手,真让我感到恐惧:

http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows

Is assigning html to javascript variable a good practice? 将html分配给javascript变量是一种好习惯吗? or I hope there is a substitute. 或希望有替代品。

There is nothing wrong with it. 没有什么问题。 After all, it is really no different then typing the same thing outside of the javascript block. 毕竟,在javascript块之外键入相同的内容确实没有什么不同。

I do however find, that the formatting and the likes can be annoying. 但是,我确实发现格式和类似内容可能令人讨厌。 On use JQuery a fair bit, and depending on what I might be doing I might use a .html() or .clone() method to create html form another element. 在使用JQuery时,要注意一点,根据我可能在做什么,我可能会使用.html().clone()方法来创建另一个元素组成的html。

JQuery also has a template plugin which when used does allow for you to get slightly better formatting, and you can also specify dynamic values. JQuery还有一个模板插件 ,使用该插件确实可以使您获得更好的格式,并且还可以指定动态值。 Which is great for creating dynamic tables that update with Ajax for example. 例如,这对于创建使用Ajax更新的动态表非常有用。

Another side note, the fact that example you gave was on a Google site, would usually be enough to convince me it is OK to do ;) 另一个注意事项是,您所举的示例位于Google网站上,通常足以说服我可以这样做;)

There's nothing bad in it. 没有什么不好的。 People have been doing this since there was a thing called DHTML :-) 人们一直在这样做,因为有一种叫做DHTML的东西:-)

AFAIK, this is one of the most performant ways to build a part of document (later to be inserted to DOM or whatever). AFAIK,这是构建文档一部分(后来插入DOM或其​​他对象)的最有效方法之一。

In this case you have to, since google Maps API requires explicitly to pass a HTML content (and not a reference to some hidden element in page or loaded via ajax). 在这种情况下,您必须这样做,因为Google Maps API明确要求传递HTML内容(而不是对页面中某些隐藏元素的引用或通过Ajax加载的引用)。

This don't mean it's a bad practice: for example, I always use a HTML string along with some custom template system, so that I can pass infowindow HTML in a loop, changing dynamically some chunks of markup with data retrieved by a JSON. 这并不意味着这是一个坏习惯:例如,我总是将HTML字符串与一些自定义模板系统一起使用,以便可以循环传递infowindow HTML,并使用JSON检索的数据动态更改一些标记块。

Anyway you can still use an element into the DOM and then pass its outerHTML string to the API if this makes your application more performant with an improved maintainability 无论如何,您仍然可以在DOM中使用元素,然后将其outerHTML字符串传递给API,如果这样可以使您的应用程序性能更高且可维护​​性更高

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM