我正在尝试编写一个可重用的脚本,用于在单击时切换元素的文本。
我可以点击它,但无法将其切换回来。我的 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
此外,是否有更干净的方法来重构它?我使用数据属性来确定新文本,而不是使用 ID 并为每个要使用它的元素编写单独的脚本。数据属性方法是一个好方法吗?
最佳答案
$('.js-textEdit').click(function () {
var oldText = $(this).text();
var newText = $(this).data('text');
$(this).text(newText).data('text',oldText);
});
<强> jsFiddle example (还有一个稍微 better example 以展示它如何在多个元素上工作)
关于javascript - 使用 jQuery 单击时切换跨度文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22359097/