如何使用jQuery更改元素中的文本?

时间:2017-05-22 18:53:30

标签: javascript jquery replace

我有这段代码(只有相关部分):

<script>
        $(function() {
            $('ul li').click(function() {
                $(this).addClass('picked').siblings().removeClass('picked');
            });
        });
        $('picked').click(function() {
            var $this = $(this);
            $this.toggleClass('picked');
            if ($this.hasClass('picked > rightPill-right')) {
                this.textContent = this.textContent.replace('Pick This One!', 'Got It!')
            };
        });
    </script>
<div class="timePill ">
  <div class="timePill-left ">
    <p>4:30 PM - 6:30 PM</p>
  </div>
  <div class="timePill-right">
    <input type="radio" autocomplete="off" value="430">
    <p>Pick This One!</p>
  </div>
</div>

我的想法是,当有人选择元素时,这是一个单选按钮,而不是“选择这个”,它应该读取“Got It”。但是,我无法使其发挥作用。我做错了什么?

2 个答案:

答案 0 :(得分:2)

你可以使用check和next兄弟选择器

来完成CSS

input[type="radio"] + label + label { display: none }
input[type="radio"]:checked + label { display: none }
input[type="radio"]:checked + label + label { display: inline }
<div class="timePill ">
  <div class="timePill-left ">
    <p>4:30 PM - 6:30 PM</p>
  </div>
  <div class="timePill-right">
    <input type="radio" autocomplete="off" value="430" id="r1" name="foo">
    <label for="r1">Pick This One!</label>
    <label for="r1">Got It!</label>
  </div>
</div>

<div class="timePill ">
  <div class="timePill-left ">
    <p>4:30 PM - 6:30 PM</p>
  </div>
  <div class="timePill-right">
    <input type="radio" autocomplete="off" value="430" id="r2" name="foo">
    <label for="r2">Pick This One!</label>
    <label for="r2">Got It!</label>
  </div>
</div>

答案 1 :(得分:0)

您的代码和HTML似乎与一个示例不匹配,但无论如何您可以执行以下操作:

$('input').click(function () {
  $(this).parent().find('p').text('...');
}