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

痞子三分冷 提交于 2020-01-30 06:06:07

问题


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...


回答1:


Try this:

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/5575529/how-do-you-switch-between-two-texts-in-one-jquery-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!