我有一个小问题。我有几个按钮,每个按钮都有不同的data-function=""
属性。我想执行一个小脚本来检查单击了哪个按钮。
<a href="#" class="functionButton" data-function="blogFunctionaliteit">Blog</a>
<a href="#" class="functionButton" data-function="offerteFunctionaliteit">Offerte</a>
<a href="#" class="functionButton" data-function="overzichtFunctionaliteit">Offerte</a>
我只想要一个脚本,上面写着
if $(this) has <data-function="blogFunctionaliteit"> { }
if $(this) has <data-function="offerteFunctionaliteit"> { }
if $(this) has <data-function="overzichtFunctionaliteit"> { }
else { // do nothing }
我已经尝试了很多东西,但是一切似乎都没有用,包括
if ($(this).attr('data-function', 'blogFunctionaliteit') { }
-结果始终为“ yes”,因为它仅检查对象是否具有第一个参数,而不是同时检查这两个参数。
在此先感谢您编写正确的jQuery代码,或者可以建议我使用其他代码。
对于较短的方法,请尝试以下操作:
if ($(this).data("function") === 'blogFunctionaliteit') {
// TODO: enter your code...
} else if ($(this).data("function") === 'offerteFunctionaliteit') {
// TODO: enter your code...
} else if ($(this).data("function") === 'overzichtFunctionaliteit') {
// TODO: enter your code...
} else {
// do nothing
}
同时,我在JavaScript方面积累了很多经验,并对自己的代码建议进行了一些改进。如果有人在阅读此答案,我强烈建议您使用以下代码:
var self = this;
var $self = $(self);
var dataFunction = $self.attr('data-function');
switch (dataFunction) {
case 'blogFunctionaliteit':
// TODO: enter your code...
break;
case 'offerteFunctionaliteit':
// TODO: enter your code...
break;
case 'overzichtFunctionaliteit':
// TODO: enter your code...
break;
default:
// do nothing
break;
}
但是,为什么要使用此功能呢?它要复杂得多!好吧,是的,但是这是为什么:
this
在变量中,因为this
可能与您想像的不一样,请查看以下链接:https : //developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this$(...)
一次jQuery函数(),然后将其存储在新变量中以提高性能。对象功能相同。相信我,如果您像第二个代码片段一样开始编写代码,那么JavaScript的问题就会减少。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句