jquery:替换文本并单击重置

时间:2013-10-10 08:56:43

标签: jquery text replace

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

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;
});

我的问题是,如果点击其他项目,我需要“重置”文字。我需要什么呢?

以下是CodePen上的工作 - http://codepen.io/sturobson/pen/zbunG

4 个答案:

答案 0 :(得分:2)

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

<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

答案 1 :(得分:1)

试试这个:演示 http://jsfiddle.net/ZPaU6/

正在使用的API:

休息这应该有助于我认为:)的原因 的代码

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

答案 2 :(得分:0)

尝试

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

$('.bbb').each(function(){
    var $this = $(this);
    $this.data('text', $this.text())
})
$('.reset').click(function () {
    $('.bbb').text(function (_, oldText) {
        return $(this).data('text');
    });
})

演示:Fiddle

答案 3 :(得分:0)

我建议您使其灵活并使用数据属性,以便不将字符串限制为存储在JS中的字符串,并且每次都不会遍历dom来考虑性能。

<强> HTML:

<div class="aaa">
  <p class="bbb" data-original="Hello" data-alternative="Goodbye">Hello</p>
</div>
<div class="aaa">
  <p class="bbb" data-original="Hello" data-alternative="Goodbye">Hello</p>
</div>
<div class="aaa">
  <p class="bbb" data-original="Hello" data-alternative="Goodbye">Hello</p>
</div>

<强> JS:

// Store the elems in vars for quicker access
var $aaa = $('.aaa'),
    $bbb = $('.bbb');

// Loop through each click to get the index
$aaa.each(function(index) {
  $(this).on('click', function(e) {
    e.preventDefault();

    // Find the corresponding $bbb using the index of stored var
    var $currBBB = $bbb.eq(index);

    // If the text is the alternative text, do nothing
    if ($currBBB.text() === $currBBB.data('alternative')) {
      return;
    }

    // Otherwise, loop through $bbb's and reset their text to the original
    $bbb.each(function() {
      var $this = $(this);
      $this.text($this.data('original'));
    });

    // Set the relevant $bbb to the alternative text
    $currBBB.text($currBBB.data('alternative'));
  });
});

工作示例:http://codepen.io/stowball/pen/uBqlE