在javascript/DOM中存储文本内容的最快和/或最干净的方法是什么?

时间:2022-12-08 12:01:31

I typically see version 1 but some open source projects I work on use version 2 and I've used version 3 in the past. Does anyone have a more elegant solution, maybe one that's more scalable?

我通常会看到版本1,但是我在使用版本2时使用过一些开源项目,我过去也使用过版本3。有人有更优雅的解决方案吗,也许是更可扩展的?

Version 1:

版本1:

var text1 = 'this is my script\'s content';

Version 2:

版本2:

<script type="text/plain" id="text1">This is my content</script>
<script> var text1 = $('#text1').html(); </script>

Version 3:

版本3:

<input type="hidden" id="text1" value="this is my content">
<script> var text1 = $('#text1').val(); </script>

Version 4:

版本4:

<span class="hidden" id="text1">this is my content</span>

3 个解决方案

#1


7  

v1, because it is the ONLY way to store text in JavaScript. Everything else you've listed is storing text in DOM.

因为这是在JavaScript中存储文本的唯一方法。您列出的其他所有内容都是在DOM中存储文本。

DOM is "presentation" and it is generally bad idea to mix "data" and "presentation". For example when you implement collision in 3D FPS, you will never scan models from screen (presentation), you'll compare their coordinates in their data instead.

DOM是“表示”,混合“数据”和“表示”通常不是个好主意。例如,当您在3D FPS中实现碰撞时,您将永远不会从屏幕上扫描模型(表示),而是在数据中比较它们的坐标。

#2


4  

I've never used v2. I only use v3 & v4 when communicating with backend, in case they need to send me a variable to be used in my JS. But for anything I work on, I use v1 - there's no need to pollute your html. Separation of interaction and content. Also, I switch between double and single quotes depending on my content. No need for all the escape slashes.

我从来没有使用v2。我只在与后端通信时使用v3和v4,以防他们需要向我发送一个要在我的JS中使用的变量。但是对于我所做的任何工作,我使用v1——没有必要污染您的html。交互和内容的分离。另外,我根据内容在双引号和单引号之间切换。不需要所有的逃避。

#3


0  

storing text as in version 1 is good as rest store data in DOM

在版本1中存储文本与在DOM中存储rest数据一样好

#1


7  

v1, because it is the ONLY way to store text in JavaScript. Everything else you've listed is storing text in DOM.

因为这是在JavaScript中存储文本的唯一方法。您列出的其他所有内容都是在DOM中存储文本。

DOM is "presentation" and it is generally bad idea to mix "data" and "presentation". For example when you implement collision in 3D FPS, you will never scan models from screen (presentation), you'll compare their coordinates in their data instead.

DOM是“表示”,混合“数据”和“表示”通常不是个好主意。例如,当您在3D FPS中实现碰撞时,您将永远不会从屏幕上扫描模型(表示),而是在数据中比较它们的坐标。

#2


4  

I've never used v2. I only use v3 & v4 when communicating with backend, in case they need to send me a variable to be used in my JS. But for anything I work on, I use v1 - there's no need to pollute your html. Separation of interaction and content. Also, I switch between double and single quotes depending on my content. No need for all the escape slashes.

我从来没有使用v2。我只在与后端通信时使用v3和v4,以防他们需要向我发送一个要在我的JS中使用的变量。但是对于我所做的任何工作,我使用v1——没有必要污染您的html。交互和内容的分离。另外,我根据内容在双引号和单引号之间切换。不需要所有的逃避。

#3


0  

storing text as in version 1 is good as rest store data in DOM

在版本1中存储文本与在DOM中存储rest数据一样好