How do you switch between two texts in one jQuery call?

前端 未结 4 1603
有刺的猬
有刺的猬 2021-01-20 08:28

Let\'s say you have a .click() call. What code could you write inside of that .click() call so that each time you click the selected element, you c

相关标签:
4条回答
  • 2021-01-20 08:59

    Try something along these lines:

    $element.bind('click', function() {
        $(this).html($(this).html() == 'string1' ? 'string2' : 'string1');
    });
    

    Edit - 2020-01-28

    Note that bind() is now deprecated. You should be using on() instead, as of jQuery 1.7+:

    $element.on('click', function() {
      $(this).text((i, t) => t == 'string1' ? 'string2' : 'string1');
    });
    
    0 讨论(0)
  • 2021-01-20 08:59

    Try this:

    $('#someElement').toggle(function(){
       $(this).text('text1');
      }, 
     function(){
       $(this).text('text2');
     }
    );
    
    0 讨论(0)
  • 2021-01-20 09:06

    Say your clickableElement is a button and you want to toggle the button's text/label:

    $('#clickableElement').click(function() {
        var originalValue = $(this).val();
        $(this).val(originalValue == 'string1' ? 'string2' : 'string1');
    });
    
    0 讨论(0)
  • 2021-01-20 09:12
    $('#togglep').on('click', function(){
      $(this).text(function(st1,st2){
        if (st2=='MARKO'){return 'POLO'};
        return 'MARKO'
      })
    })
    
    0 讨论(0)
提交回复
热议问题