How to bind a class on click event of elements obtained through a loop?

删除回忆录丶 提交于 2021-02-19 08:05:07

问题


I go through an array of objects to display in my html some information boxes that are selectable. For it I bind a class in the event click, but as I obtain the elements through a v-for, when I select one it bind the class to all of them.

How can I differentiate only the selected one?

I have seen several examples with jquery but I would like to know if there is any other method.

My template:

<div class="list-services">
  <div class='column-service' 
    v-for='estimation in filteredEstimation' 
    v-bind:key="estimation.name" 
    :class="{ focusService }" 
    @click="focusService = !focusService"
  >
    <div class="service-name">
      {{estimation.name}}
    </div>
    <div class="service-description">
      {{estimation.description}}
    </div>
    <div class="service-price">
      {{estimation.price}} 
      <span class="price-currency">€</span>
    </div>
  </div>
</div>

Thank you very much for your time and help.


回答1:


I was trying to make a jsfiddle to answer your question, but then I found this jsfiddle on the vue.js forum: https://jsfiddle.net/mogtfpze/2/

It offers three different options for highlighting content by clicking.

li v-for="item in items" 
  :class="{highlight:item.id == selected}" 
  @click="selected = item.id">
  {{item.id}}
</li>

Although it's an old answer, I believe it should still be compatible with the current Vue version.

If not, or if something is not clear, just let me know and I'll try to help you out!




回答2:


The method that I use personally (If I understand your question correctly) is the this keyword.

For example:

index.html

<ul id="myList">
    <li>a</li>
    <li>b</li>
    <li>c</li>
</ul>

script.js (Vanilla JavaScript)

var myList = document.getElementById("myList");
    myList.addEventListener("click", function () {
    console.log(this);
    console.log(this.innerText);
});

script.js (jQuery)

var myList = $("#myList").on("click", function() {
    console.log(this);
    console.log(this.innerText);
});

In this case, using the this keyword allows us to get the innerText of the li element that was clicked by only attaching the event listener to the parent element. innerHtml is only one of many ways to use this keyword. You can see more of them by doing console.log(this) in your event listener function.

Let me know if this helps!



来源:https://stackoverflow.com/questions/63485090/how-to-bind-a-class-on-click-event-of-elements-obtained-through-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!