如何在一个jQuery调用中切换两个文本

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

本文关键字:文本 两个 一个 jQuery 调用      更新时间:2023-09-26

假设您有一个.click()呼叫。您可以在.click()调用中编写什么代码,以便每次单击所选元素时,更改两个字符串之间的文本。我假设.toggle().text()会在这里发挥作用…

试着这样做:

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

注意bind()现在已被弃用。从jQuery 1.7+开始,您应该使用on():

$element.on('click', function() {
  $(this).text((i, t) => t == 'string1' ? 'string2' : 'string1');
});

假设你的clickableElement是一个按钮,你想切换按钮的文本/标签:

$('#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'
  })
})

试试这个:

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