Javascript Vuejs 获取正在被事件调用的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33173398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:43:42  来源:igfitidea点击:

Vuejs getting the element that is being called by an event?

javascriptjqueryjsonvue.js

提问by Stephan-v

I have multiple list items that I want to toggle active classes on when they are being clicked on.

我有多个列表项,我想在单击它们时切换活动类。

<ul class="list-body">
    <li v-on="click: setFilter('style', 'pils')" v-class="active: isActive">Pils</li>
    <li>Dubbel</li>
    <li>Tripel</li>
    <li v-on="click: setFilter('style', 'Quadrupel')">Quadrupel</li>
    <li>Wit</li>
</ul>

I already have a setFilterclick function where I can add extra functionality to activate the class onClick.

我已经有一个setFilter点击功能,我可以在其中添加额外的功能来激活类onClick

setFilter: function(facet, value) {
    // Facet for style of beer(search filter)
    this.helper.addDisjunctiveFacetRefinement(facet, value).search();
},

My question is how can select the specific lielement that was clicked on and called the with setFiltermethod?

我的问题是如何选择li被点击并调用 withsetFilter方法的特定元素?

I want to set a variable for the active class falseor truefor each single lielement that has been clicked (or not clicked).

我想为活动类false或已单击(或未单击)的true每个单个li元素设置一个变量。

回答by Patrick

You can directly pass the event and the events target in your function. The target is the element you clicked on.

您可以直接在函数中传递事件和事件目标。目标是您单击的元素。

HTML:

HTML:

<ul id="demo">
    <li v-on="click: onClick">Trigger a handler</li>
    <li v-on="click: n++">Trigger an expression</li>
</ul>

JS:

JS:

var vue = new Vue({
  el: '#demo',
  data: {},
  methods: {
    onClick: function (e) {
      var clickedElement = e.target;
    }
  }
})

With your element you can do what you want. For example, if you use jQuery:

有了你的元素,你可以做你想做的。例如,如果您使用 jQuery:

$(clickedElement).siblings().removeClass('active');
$(clickedElement).addClass('active');