最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you switch between two texts in one jQuery call? - Stack Overflow

programmeradmin1浏览0评论

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 change the text between two strings. I'm assuming .toggle() and .text() would play a role here...

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 change the text between two strings. I'm assuming .toggle() and .text() would play a role here...

Share Improve this question edited Sep 14, 2019 at 8:19 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 7, 2011 at 3:15 Justin MeltzerJustin Meltzer 13.5k34 gold badges119 silver badges182 bronze badges 3
  • what two strings? what are texts? – Kon Commented Apr 7, 2011 at 3:19
  • I don't think what the actual strings are matters.... – Justin Meltzer Commented Apr 7, 2011 at 3:21
  • Oh, nevermind.. I just figured out what you meant. – Kon Commented Apr 7, 2011 at 3:29
Add a comment  | 

4 Answers 4

Reset to default 26

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

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');
});
$('#togglep').on('click', function(){
  $(this).text(function(st1,st2){
    if (st2=='MARKO'){return 'POLO'};
    return 'MARKO'
  })
})

Try this:

$('#someElement').toggle(function(){
   $(this).text('text1');
  }, 
 function(){
   $(this).text('text2');
 }
);
发布评论

评论列表(0)

  1. 暂无评论