【问题标题】:By clicking on different elements with the same css class, add css class to one of them but remove it from the others using jQuery通过单击具有相同 css 类的不同元素,将 css 类添加到其中一个,但使用 jQuery 从其他元素中删除它
【发布时间】:2021-05-31 23:59:44
【问题描述】:

我想在每次单击每个divs 并使用 jQuery 激活该元素时,在 textarea 中添加特定 div 元素的文本:

这是我的代码:

$('.msg-item-row').each(function() {
$(this).click(function(){
$(this).addClass('selected-msg');
var msgtextslot = $(this).text();
$('#message').val(msgtextslot);

//alert (msgtextslot);
});
});
.msg-item-row {
  background:#f3f5f8;
  color:#383838;
  padding:10px;
  margin-bottom:10px;
  cursor:pointer;
  transition: ease-in-out 0.2s;
  font-size:0.8rem;
}


#message {
width:90%;
padding:10px;
}

.selected-msg {
background:red;
color:#fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>


<div class="list-msg-wrapper">
<div class="msg-item-row"> Hi, i have some questions about this product. </div>
<div class="msg-item-row"> What is the most favorited color in the world? </div>
<div class="msg-item-row"> Bla bla bla bla bla</div>
</div>

<textarea id="message" name="message" rows="3" placeholder="Enter your message..."></textarea>

代码工作得很好,当我通过添加类“.selected-msg”单击它时,我可以设置每个 div 的样式。 我的问题是我不知道如何从其他两个未选中的 div 中删除该类

【问题讨论】:

标签: html jquery css


【解决方案1】:

您可以使用 jQuery 的 removeClass 从所有按钮中删除该类,然后将该类添加到所需的按钮:

$('.msg-item-row').each(function() {
  $(this).click(function(){
    $('.msg-item-row').removeClass('selected-msg');
    $(this).addClass('selected-msg');
    var msgtextslot = $(this).text();
    $('#message').val(msgtextslot);
  });
});
.msg-item-row {
  background:#f3f5f8;
  color:#383838;
  padding:10px;
  margin-bottom:10px;
  cursor:pointer;
  transition: ease-in-out 0.2s;
  font-size:0.8rem;
}


#message {
width:90%;
padding:10px;
}

.selected-msg {
background:red;
color:#fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>


<div class="list-msg-wrapper">
<div class="msg-item-row"> Hi, i have some questions about this product. </div>
<div class="msg-item-row"> What is the most favorited color in the world? </div>
<div class="msg-item-row"> Bla bla bla bla bla</div>
</div>

<textarea id="message" name="message" rows="3" placeholder="Enter your message..."></textarea>

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2020-09-05
    • 1970-01-01
    • 2018-10-20
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多