我可以返回文档的值吗?setcookie中的Getelementbyid

Can I return the value of document.getelementbyid inside a document.setcookie?

本文关键字:setcookie 中的 Getelementbyid 返回 文档 我可以      更新时间:2023-09-26
<input type=button value='Do Stuff' onClick='document.cookie = "Note_<% Response.Write(arrTest(0,i)) %> = ' + (Document.getElementById("StuffTest<% Response.Write(arrTest(0,i)) %>").value) + '"'>

我在这里要做的是当用户点击按钮时,我想要创建一个值为:Note_(arrTest的值)=(文本框的值)的cookie。

下面的代码可以正常工作:

<input type=button value='Do Stuff' onClick='document.cookie = "Note_<% Response.Write(arrTest(0,i)) %> = Awesome!"'>

它创建了一个值为:Note_(value of arrTest) = Awesome的cookie !

我做错了什么让我的文本框的值进入cookie?我认为这与所有那些令人困惑的单/双引号有关,所以我想我只是有打字盲症,但我的一部分认为我实际上不能做我在这里想做的事情。

任何想法吗?

document.getElementById有全部小写的document。您的代码示例使用Document(带有大写的D),这将失败。

另外,您在onClick属性中的引号不太正确。最好避免在这些属性中放入任何重要的代码。相反,定义并调用一个函数,像这样:

<input type=button
       value='Do Stuff'
       onClick='setCookie("<% Response.Write(arrTest(0,i)) %>);'>

…其中函数(在<script>标记内或在一个被其引用的文件中)看起来像这样:

function setCookie(name) {
    document.cookie = "Name_" + name + "=" + document.getElementById("StuffTest" + name).value;
}

根据arrTest(0,i)的内容,您可能需要在输出时对其进行HTML编码,因为您要将其输出到HTML(是的,onXYZ属性内的代码是HTML,就像任何其他属性的值一样,因此例如<需要是&lt;)。