How to add a certain value to anchor tag?

2019-02-06 18:42发布

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?

4条回答
戒情不戒烟
2楼-- · 2019-02-06 19:14

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

<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 .data instead of .attr is more appropriate

查看更多
我只想做你的唯一
3楼-- · 2019-02-06 19:20

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>
查看更多
倾城 Initia
4楼-- · 2019-02-06 19:23

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

    ` $("#click").click(function(event){console.log($(this).data("value"));});`
查看更多
不美不萌又怎样
5楼-- · 2019-02-06 19:24

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.

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

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

then get it using :

$("#link").data("myvalue")
查看更多
登录 后发表回答