How to add a certain value to anchor tag?

后端 未结 5 1152
时光说笑
时光说笑 2020-12-31 07:26

I have the following code

Inside Link which sets a value



        
相关标签:
5条回答
  • 2020-12-31 07:59

    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

    0 讨论(0)
  • 2020-12-31 08:08

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

        ` $("#click").click(function(event){console.log($(this).data("value"));});`
    
    0 讨论(0)
  • 2020-12-31 08:15

    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.

    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
    });
    
    
    0 讨论(0)
  • 2020-12-31 08:23

    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")
    
    0 讨论(0)
  • 2020-12-31 08:25

    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>
    
    0 讨论(0)
提交回复
热议问题