将javascript对象保存在HTML对象中

将javascript对象保存在HTML对象中,javascript,html,Javascript,Html,有没有办法在HTML对象中保存javascript标记?我想做的是这样的: <div id="htmlTag">some text</div> <script type="text/javascript"> htmlTag.something = {s:"a string",n:1,b:false,a:[3,2,1],f:function(){alert("hello")}} </script> 一些文本 htmlTag.somethin

有没有办法在HTML对象中保存javascript标记?我想做的是这样的:

<div id="htmlTag">some text</div>
<script type="text/javascript">
    htmlTag.something = {s:"a string",n:1,b:false,a:[3,2,1],f:function(){alert("hello")}}
</script>
一些文本
htmlTag.something={s:“字符串”,n:1,b:false,a:[3,2,1],f:function(){alert(“hello”)}

您可以使用将JS对象转换为JSON字符串,如果这是您想要实现的

var json_data = JSON.stringify(yourObj);

我想你唯一的问题是你没有得到节点

document.getElementById("htmlObject").something = {hi: 1};

您可以使用javascript函数来实现这一点

Javascript

<div id="htmlTag">some text</div>
<script type="text/javascript">
    document.getElementById('htmlTag').something = JSON.stringify({s:"a string",n:1,b:false,a:[3,2,1],f:function(){alert("hello")}});
</script>
一些文本
document.getElementById('htmlTag').something=JSON.stringify({s:a string),n:1,b:false,a:[3,2,1],f:function(){alert(“hello”)});

下面是一个JSIDLE:

为什么?你想在这里实现什么?没有“HTML对象”这样的东西。@NiettheDarkAbsol我想保存与HTML对象相关的javascript信息,但这并不直接关系到它。@DonaldDuck你说的“但这不直接关系到它”是什么意思?@guest271314如果它不存在,HTML对象将工作,并且看起来与它存在时完全相同。也就是说,除非您正在开发某种HTML/js框架,否则我无法想象这是一个好的用例。这在旧版本的IE中不起作用,我希望我的HTML与它们兼容。然后使用
document.getElementById(“htmlObject”)
实际上不需要字符串化。节点元素的处理方式与常规js对象类似,因此可以向其添加任意属性。