San*_*fer 8 comparison jquery if-statement custom-data-attribute
我有点问题.我有几个按钮,每个按钮都有不同的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>
Run Code Online (Sandbox Code Playgroud)
我只想要一个说的脚本
if $(this) has <data-function="blogFunctionaliteit"> { }
if $(this) has <data-function="offerteFunctionaliteit"> { }
if $(this) has <data-function="overzichtFunctionaliteit"> { }
else { // do nothing }
Run Code Online (Sandbox Code Playgroud)
我尝试过很多东西,但一切似乎都没有用,包括
if ($(this).attr('data-function', 'blogFunctionaliteit') { } - 总是会导致yes,因为它只检查对象是否具有第一个参数,而不是检查它们.
提前感谢您编写正确的jQuery代码或建议我使用其他东西.
Ree*_*ube 20
简而言之,试试这个:
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
}
Run Code Online (Sandbox Code Playgroud)
同时我已经获得了很多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;
}
Run Code Online (Sandbox Code Playgroud)
但你为什么要用这个呢?这要复杂得多!嗯,是的,但这就是原因:
this在变量中,因为this可能不是您认为的那样,请查看此链接:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this$(...)一次jQuery函数(),然后将其存储在一个新变量中以提高性能.对象函数也是如此.相信我,如果您开始像第二个代码片段一样编写代码,那么JavaScript的问题会更少.
你可以做:
if ($(this).attr('data-function') == 'blogFunctionaliteit') { }
Run Code Online (Sandbox Code Playgroud)