jQuery noob,但感谢StackOverflow快速学习。
任何人都可以给我一些代码,它将从表单中获取数据并使用jQuery将其写入cookie(而不是会话cookie)。我从这里加载jQuery cookie插件:
https://github.com/carhartl/jquery-cookie
我还想知道我是否必须在DOM准备好之前加载我的代码,就像之前使用php我首先加载了cookie一样。无法绕过DOM。
好的,这是当前的代码,感谢下面的回复。我不能让cookie工作,但是当取消注释时警报工作正常:
<form id="myform">
<fieldset>
<h3>Search</h3>
<p>
<label>Your search *</label>
<input type="text" id="mysearch" pattern="[a-zA-Z ]{5,}" maxlength="30" />
</p>
<fieldset>
<input type="range" id="range" min="1" max="30" value="10" />
<input type="range" id="range2" min="30" max="9000" value="2000" />
</fieldset>
<button id="subbtn" type="submit">Submit form</button>
<button type="reset">Reset</button>
</fieldset>
</form>
$(function() {
// initialize tooltip
$(".imgwrap").tooltip({
//$(".tooltip").tooltip({ effect: 'slide'});
// tweak the position
offset: [10, 2],
// use the "slide" effect
effect: 'slide'
// add dynamic plugin with optional configuration for bottom edge
}).dynamic({ bottom: { direction: 'down', bounce: true } });
});
//this one loads the form validator
$("#myform").validator();
//this one for the slider
$(":range").rangeinput();
$("#subbtn").on("click", function () {
// alert("Cookie!");
$.cookie('Searchitem', $("#mysearch").val(), { expires: 365 });
});
为什么我的cookie没有设置的任何想法?浏览器设置为接受,我正在使用Firebug进行调试。
答案 0 :(得分:1)
持久性cookie与会话cookie相同,但它具有过期日期,因此它会挂起。
这会将输入的文本值写入365天过期的cookie:
<input id="txt" type="text" value="foo" />
<input id="btn" type="button" value="write cookie" />
...
$(document).ready(function () {
$("#btn").on("click", function () {
$.cookie('myCookie', $("#txt").val(), { expires: 365 });
});
});
修改强>
每个更新问题的新代码:
$(function () {
// initialize tooltip
$(".imgwrap").tooltip({
//$(".tooltip").tooltip({ effect: 'slide'});
// tweak the position
offset: [10, 2],
// use the "slide" effect
effect: 'slide'
// add dynamic plugin with optional configuration for bottom edge
}).dynamic({ bottom: { direction: 'down', bounce: true} });
//this one loads the form validator
$("#myform").validator();
//this one for the slider
$(":range").rangeinput();
$("#subbtn").on("click", function () {
// alert("Cookie!");
$.cookie('Searchitem', $("#mysearch").val(), { expires: 365 });
});
});
答案 1 :(得分:0)
我假设您要使用GET提交表单。您可以使用描述here的方法来提取URL字符串值。
然后只需将值设置为cookie:
$.cookie('mycookie', getParameterByName('varname'), {expires: 100});
您可以像这样检查cookie的值:
console.log($.cookie('mycookie'));