jQuery:替换文字并在点击时重置 [英] jquery: replace text and reset on click

查看:87
本文介绍了jQuery:替换文字并在点击时重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个可点击的项目,需要在点击时更改文字.

I've got a 3 items that are clickable and need to have the text changed on click.

HTML

<div class="aaa">
  <p class="bbb">Hello</p>
</div>
<div class="aaa">
  <p class="bbb">Hello</p>
</div>
<div class="aaa">
  <p class="bbb">Hello</p>
</div>

和jQuery

$('.aaa').on("click", function() {
  $('.bbb', this).text(function(_, oldText) {
    return oldText === 'Hello' ? 'Goodbye' : 'Hello';
  });
  return false;
});

我的问题是,如果我单击其他项目,则需要重置"文本.我需要什么?

My problem is I need to 'reset' the text if I click a different item. What do I need for this?

到目前为止,这是有关CodePen的工作- http://codepen.io/sturobson/pen/zbunG

Here's the work so far on CodePen - http://codepen.io/sturobson/pen/zbunG

推荐答案

您可以将data-*属性添加到元素并将原始文本存储在这些属性中;

You can add data-* attribute to the elements and store the original texts in those attributes;

<div class="aaa">
  <p class="bbb" data-text='Hello'>Hello</p>
</div>
<div class="aaa">
  <p class="bbb" data-text='Hello'>Hello</p>
</div>
<div class="aaa">
  <p class="bbb" data-text='Hello'>Hello</p>
</div>

$('.aaa').on("click", function() {
   $('.bbb', this).text(function(_, oldText) {
       return oldText === 'Hello' ? 'Goodbye' : 'Hello';
   }).parent().siblings().find('.bbb').text(function(){
       return $(this).data('text');
   });
   return false;
});

http://codepen.io/anon/pen/LDudE

这篇关于jQuery:替换文字并在点击时重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆