jQuery - disable and enable an anchor tag based on condition

后端 未结 6 967
有刺的猬
有刺的猬 2021-01-25 01:10

On page load, I am checking to see if a person is registered. If he is then, I will enable a link otherwise disable the link.

I tried the following , but it doesnt work.

相关标签:
6条回答
  • 2021-01-25 01:21

    Try this, if user is register then enable the link by adding href, if not then disable by removing the href attribute.

    Just set the status to some string before executing this code.

    var href = $('#addlink').attr('href');
    if(status == 'Registered'){
        $('#addlink').attr('href', href);
    } else{
        $('#addlink').removeAttr('href');
    }
    

    Check here.

    0 讨论(0)
  • 2021-01-25 01:26

    An alternative based on CSS would be

    $('#addlink').css('pointer-events', 'none');
    

    CanIUse reports a 94% support of this feature as of early 2017.

    0 讨论(0)
  • 2021-01-25 01:27

    Why don't you use the javascript:void(0) ?

    <a href="javascript:void(0)"> Link </a>
    

    like

    var href = 'javascript:void(0)';
    
    var status = $('#status').val();  // ??
    if (status == 'Registered'){
        href = 'available link';
    }
    
    $('#addlink').attr('href',href);
    
    0 讨论(0)
  • 2021-01-25 01:33

    use event.preventDefault to prevent anchor tag to work.

    anchor tag doesn't disable on adding attribute disabled

    var status = $('#status').text(); // get text value if it's is span/div/p etc
    if (status == 'Registered') {
        $('#addlink').click(function (e) {
            e.preventDefault();
        });
    } 
    
    0 讨论(0)
  • 2021-01-25 01:36
    var status = $('#status').val(); //Not sure if it is a value/text
    $('#addlink').on('click', function (e) {
        if (status == 'Registered') {
            e.preventDefault(); // prevent the default action of anchor tag
            return false;
        }
    });
    
    0 讨论(0)
  • 2021-01-25 01:39

    If you really want to remove the link you can use jquery unwrap method.

    $("yourlinkselector").contents().unwrap();
    

    This will remove the link. To add it back again you might have to put the link text into a span, give it a name and use .wrap to wrap it around your content.

    Working example can be found here: http://jsfiddle.net/Elak/hrvPj/2/

    // remove the link
    $(".link").contents().unwrap().wrap("<span class='oldLink'></span>")
    
    // add the link again and remove the temp span
    $(".oldLink").contents().unwrap().wrap("<a href='#'></a>");
    
    0 讨论(0)
提交回复
热议问题