使用jQuery单击切换文本

col*_*ite 0 javascript jquery

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

我可以点击它,但无法切换回去。我的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);
  }
});
Run Code Online (Sandbox Code Playgroud)

这是一个JSFIddle

另外,有没有更干净的方法来重构它?我使用数据属性来确定新文本,而不是使用ID并为要使用的每个元素编写单独的脚本。数据属性方法是一种好方法吗?

j08*_*691 5

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

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