jquery – 如何使用’如果$(this)具有数据属性’

我有点问题.我有几个按钮,每个按钮都有不同的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;
}

但你为什么要用这个呢?这要复杂得多!嗯,是的,但这就是原因:

>您应该始终将其存储在变量中,因为这可能不是您认为的那样,请查看此链接https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this
>您应该只调用一次jQuery函数($(…)),然后将其存储在一个新变量中以提高性能.对象函数也是如此.
>对于这种情况,最好使用switch-case结构,请查看此链接Case vs If Else If: Which is more efficient?

相信我,如果您开始像第二个代码片段一样编写代码,那么JavaScript的问题会更少.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...