Calling the strike function (after the select) function, I get the following error:
调用strike函数(在select之后)函数,我得到以下错误:
Uncaught ReferenceError: selected is not defined
未捕获的ReferenceError:未定义选定的
methods: {
select: function(event) {
selected = event.target.id
},
strike: function(event) {
$(selected).toggleClass('strike')
}
}
This works using JavaScript, document.getElementById(selected).classList.add('strike')
but not JQuery.
这可以使用JavaScript,document.getElementById(选中).classList.add('strike')而不是JQuery。
How to I define selected
for jQuery to access?
如何定义为jQuery选择访问?
2 个解决方案
#1
1
Instead of having to query the DOM again, it'd be better if you save a reference to the actual element:
而不是必须再次查询DOM,如果您保存对实际元素的引用会更好:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
$(this.selected).toggleClass('strike');
}
}
If you don't have to support old IE browsers, you can forgo jQuery here completely by using the classList
property:
如果您不必支持旧的IE浏览器,可以使用classList属性完全放弃jQuery:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
this.selected.classList.toggle('strike');
}
}
Finally, there should be a way to handle all this through Vue's :class
binding in the template itself. If you'd show us the template, we may help you improve it.
最后,应该有办法通过Vue处理所有这些:模板本身中的类绑定。如果您向我们展示模板,我们可能会帮助您改进模板。
#2
1
Because $()
is expecting a CSS selector string. Add #
to denote it is an id
.
因为$()期望一个CSS选择器字符串。添加#表示它是一个id。
$("#" + selected).toggleClass('strike')
#1
1
Instead of having to query the DOM again, it'd be better if you save a reference to the actual element:
而不是必须再次查询DOM,如果您保存对实际元素的引用会更好:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
$(this.selected).toggleClass('strike');
}
}
If you don't have to support old IE browsers, you can forgo jQuery here completely by using the classList
property:
如果您不必支持旧的IE浏览器,可以使用classList属性完全放弃jQuery:
methods: {
select: function(event) {
this.selected = event.target;
},
strike: function() {
this.selected.classList.toggle('strike');
}
}
Finally, there should be a way to handle all this through Vue's :class
binding in the template itself. If you'd show us the template, we may help you improve it.
最后,应该有办法通过Vue处理所有这些:模板本身中的类绑定。如果您向我们展示模板,我们可能会帮助您改进模板。
#2
1
Because $()
is expecting a CSS selector string. Add #
to denote it is an id
.
因为$()期望一个CSS选择器字符串。添加#表示它是一个id。
$("#" + selected).toggleClass('strike')