jQuery 如何为锚标记添加某个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9148432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:24:51  来源:igfitidea点击:

How to add a certain value to anchor tag?

jquerytagsjquery-animatehref

提问by Alex G.

I have the following code

我有以下代码

<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>

And i want to add a value attribute to an anchor tag. How to do it?

我想向锚标记添加一个值属性。怎么做?

回答by Andrew Hymanman

If you want to add a random attribute for a value, you can use data attributes:

如果要为值添加随机属性,可以使用数据属性:

<a href="#" data-value="1">Text</a>

<script type="text/javascript">
$("a").click(function(){
    i=$(this).data("value");
    $('#square').animate({'left': i * 360});
});
</script>

回答by Oybek

If you are using HTML5 you can use the data-technique.

如果您使用的是 HTML5,则可以使用该data-技术。

<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.
});

EDIT

编辑

Usage of .datainstead of .attris more appropriate

使用.data而不是.attr更合适

回答by Mouna Cheikhna

you can use custom data attributes see this.

你可以使用自定义数据属性看到这个

<a href="#" data-json="{ 'myValue':'1'}">Click</a> //you can even pass multiple values there.

then access it using data() function.

然后使用 data() 函数访问它。

Or instead of using json you can put it as an attribute :

或者,您可以将其作为属性,而不是使用 json:

<a href="link"  myvalue="1"">

then get it using :

然后使用:

$("#link").data("myvalue")

回答by Kartikeya Sharma

<a href="#" data-value="IE" id="click">Click</a>

<a href="#" data-value="IE" id="click">Click</a>

    ` $("#click").click(function(event){console.log($(this).data("value"));});`

回答by Yuvraj Choudhary

data-value is a good attribute. but.. You can also add a " rel " attribute to your anchor tag. it describes the relation to the document where the link points to. And you can also use it to store a value.

数据值是一个很好的属性。但是.. 你也可以给你的锚标签添加一个“rel”属性。它描述了与链接指向的文档的关系。你也可以用它来存储一个值。

Like This -

像这样 -

$("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
});