Jquery 如何为锚定标记添加特定值?
我有以下代码Jquery 如何为锚定标记添加特定值?,jquery,tags,jquery-animate,href,Jquery,Tags,Jquery Animate,Href,我有以下代码 <a href="" (set value 1)>Inside Link which sets a value</a> <script> $(a).click(function() { i=value of a tag; $('#square').animate({'left': i * 360}); }); </script> $(a)。单击(函数(){ i=标签的值; $('#square')。动画({'l
<a href="" (set value 1)>Inside Link which sets a value</a>
<script>
$(a).click(function() {
i=value of a tag;
$('#square').animate({'left': i * 360});
});
</script>
$(a)。单击(函数(){
i=标签的值;
$('#square')。动画({'left':i*360});
});
我想给锚点标记添加一个value属性。如何操作?如果要为值添加随机属性,可以使用数据属性:
<a href="#" data-value="1">Text</a>
<script type="text/javascript">
$("a").click(function(){
i=$(this).data("value");
$('#square').animate({'left': i * 360});
});
</script>
$(“a”)。单击(函数(){
i=$(此).data(“值”);
$('#square')。动画({'left':i*360});
});
如果您使用的是HTML5,您可以使用数据-
技术
<a id="target" href="http://foo.bar" data-custom-value="1">Text</a>
$("#target").click(function() {
var value = $(this).data("custom-value");
// do other stuff.
});
$(“#目标”)。单击(函数(){
var值=$(此).data(“自定义值”);
//做其他事情。
});
编辑
使用
.data
而不是.attr
更合适您可以使用自定义数据属性,请参见
数据值是一个很好的属性。但是 您还可以将“rel”属性添加到锚标记中。 它描述了链接指向的文档的关系。您还可以使用它来存储值 像这样-
$("a").click(function(){
var page = $(this).attr('rel'); // save the attribute value here
sessionStorage.setItem("text",page);
/*save it in session storage if you want to send (or retrieve) this value to another page.
if not then use it easily without saving it in session storage*/
//Use it here
return false; // to stop the redirection if <a> contains a link
});
$(“a”)。单击(函数(){
var page=$(this.attr('rel');//在此处保存属性值
setItem(“文本”,第页);
/*如果要将此值发送(或检索)到另一页,请将其保存在会话存储中。
如果没有,则可以轻松使用它,而无需将其保存在会话存储中*/
//在这里使用它
return false;//如果包含链接,则停止重定向
});
@gdoron我本来想提到这一点,但后来我看了一下jQuery的文档,他们说.attr(“数据自定义值”)
没有问题,.data()
仅在您也将为其设置值时才被鼓励。如何设置rel-in的值???下面,如果我有这样的东西。函数(值){return Export}
<a href="link" myvalue="1"">
$("#link").data("myvalue")
` $("#click").click(function(event){console.log($(this).data("value"));});`
$("a").click(function(){
var page = $(this).attr('rel'); // save the attribute value here
sessionStorage.setItem("text",page);
/*save it in session storage if you want to send (or retrieve) this value to another page.
if not then use it easily without saving it in session storage*/
//Use it here
return false; // to stop the redirection if <a> contains a link
});