0

我试图修改这个脚本

http://www.dynamicdrive.com/dynamicindex16/formremember2.htm

为文本区域工作,而不仅仅是输入文本框。继承人我猜是脚本的相关部分,我自己想不通

rememberForm.prototype.savevalues=function(){ //get form values and store in cookie
for (var i=0; i<this.fields.length; i++){
if (this.fields[i].type=="text")
this.cookiestr+=this.fields[i].fname+":"+escape(this.fields[i].value)+"#"
}
if (typeof this.togglebox!="undefined"){ //if "remember values checkbox" is defined
this.persistdays=(this.togglebox.checked)? this.persistdays : -1 //decide whether to       save form values
this.cookiestr=(this.togglebox.checked)? this.cookiestr+"toggleboxid:on;" :   this.cookiestr
}
else //if checkbox isn't defined, just remove final "#" from cookie string
this.cookiestr=this.cookiestr.substr(0, this.cookiestr.length-1)+";"
setCookie(this.cookiename, this.cookiestr, this.persistdays)
}

rememberForm.prototype.recallvalues=function(){ //populate form with saved values
var cookievalue=getCookie(this.cookiename)
if (cookievalue!=""){ //parse cookie, where cookie looks like:  field1:value1#field2:value2...
var cookievaluepair=cookievalue.split("#")
for (var i=0; i<cookievaluepair.length; i++){
if (cookievaluepair[i].split(":")[0]!="toggleboxid" && this.getfield(cookievaluepair[i].split(":")[0]).type=="text")
this.getfield(cookievaluepair[i].split(":")         [0]).value=unescape(cookievaluepair[i].split(":")[1])
else //else if name in name/value pair is "toggleboxid"
this.togglebox.checked=true
}
}
4

1 回答 1

0

该方法persistfields(id, ...)设置您想要保留在 cookie 中的字段。这些字段是通过查找的,id所以我想添加一个textarea带有id属性的就足够了。

例如:

<form id="myFormId">
    <input type="text" id="someInputId" />
    <textarea id="textareaId"></textarea>
</form>

<script>
    var f = new rememberForm('myFormId');
    f.persistfields('someInputId', 'textareaId');
</script>

这会将输入和文本区域添加到rememberForm实例fields属性。


更新

问题出在这种方法上rememberForm。我对代码进行了格式化以提高可读性,因为原始源的格式很糟糕。

rememberForm.prototype.savevalues = function() {

    for (var i = 0; i < this.fields.length; i++) {

        // PROBLEM: only allows type="text"
        if (this.fields[i].type == "text") {
            this.cookiestr += this.fields[i].fname + " : " + escape(this.fields[i].value) + "#"
        }
        if (typeof this.togglebox != "undefined") {
            this.persistdays = (this.togglebox.checked) ? this.persistdays : -1;
            this.cookiestr = (this.togglebox.checked) ? this.cookiestr + "toggleboxid:on;" : this.cookiestr
        } else {
            this.cookiestr = this.cookiestr.substr(0, this.cookiestr.length - 1) + ";"
            setCookie(this.cookiename, this.cookiestr, this.persistdays)
        }
    }
}

正如我在评论中提到的,它将测试输入元素的类型为“文本”。如果您想在 cookie 中添加 textareas,您可以将该行更改为:

if (this.fields[i].type == "text" || this.fields[i].type == 'textarea') {

那应该行得通。

于 2013-04-08T22:06:30.010 回答