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
Vuejs getting the element that is being called by an event?
提问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 setFilter
click 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 li
element that was clicked on and called the with setFilter
method?
我的问题是如何选择li
被点击并调用 withsetFilter
方法的特定元素?
I want to set a variable for the active class false
or true
for each single li
element 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');