jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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的问题会更少.

大佬总结

以上是大佬教程为你收集整理的jquery – 如何使用’如果$(this)具有数据属性’全部内容,希望文章能够帮你解决jquery – 如何使用’如果$(this)具有数据属性’所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。