使用jQuery在单击时切换span文本

Toggle span text on click with jQuery

本文关键字:span 文本 jQuery 单击 使用      更新时间:2023-09-26

我正在尝试编写一个可重用的脚本,用于在单击时切换元素的文本。

我有它工作的点击,但我不能让它切换回来。我的if语句有什么问题吗?

<span class="js-textEdit" data-text="Show less">Show more</span>

$('.js-textEdit').click(function() {
  var oldText = $(this).text();
  var newText = $(this).attr('data-text');
  if ($(this).text(oldText)) {
    $(this).text(newText);
  } else {
    $(this).text(oldText);
  }
});

这是一个JSFIddle

还有,是否有更干净的方法来重构它?我使用data属性来确定新文本,而不是使用id,并且必须为我想要使用它的每个元素编写单独的脚本。数据属性方法是一个好方法吗?

$('.js-textEdit').click(function () {
    var oldText = $(this).text();
    var newText = $(this).data('text');
    $(this).text(newText).data('text',oldText);
});

jsFiddle示例(以及一个稍微更好的示例,以显示它如何在多个元素上工作)

您必须将数据集设置为旧文本。

   $(this).attr('data-text',oldText);

JS小提琴