Reputation: 3439
I am trying to do something to the anchor tag (with jQuery), like change it's color when clicked but I can't seem to get the right target.
<a v-on:click="action($event)">
<span>entry 1</span>
<span>entry 2</span>
</a>
The event.target in action is either the first or second span, never the a tag.
For example
$( $event.target ).css( "backgroundColor", "red" )
Every time I click on "a" tag - one of the spans will turn red but not the actual "a" tag that has the v-on:click directive. Is there a way to target the actual element where the click directive is?
Upvotes: 3
Views: 1127
Reputation: 3257
Instead of $event.target
you have to use $event.currentTarget
. Then you assign your style to the a
-tag.
new Vue({
el: "#app",
methods: {
action: function($event){
$($event.currentTarget).css( "backgroundColor", "red" )
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app">
<a v-on:click="action($event)">
<span>entry 1</span>
<span>entry 2</span>
</a>
</div>
Upvotes: 3
Reputation: 1006
Why are you using jQuery in combination with vuejs? If you use the power of vuejs, you can do something like this:
.clicked {
background-color: red;
}
<a v-on:click="aClicked = true" :class="{ 'clicked': aClicked }">
<span>entry 1</span>
<span>entry 2</span>
</a>
Upvotes: 2