当通过Jquery data()附加时,以及当直接通过HTML中的数据属性附加时,检查HTML元素中的数据()

Checking for data() in an HTML element both when attached though the Jquery data() and also when attached through data-attributes in the HTML directly

本文关键字:HTML 数据属性 元素 数据 检查 data Jquery      更新时间:2024-04-03

我是Jquery的新手,所以我只是在尝试构建一个小插件,问题是它将广泛使用data()属性。我浏览了几次Jquery文档。但我有一个小问题一直存在。

我有以下HTML:

    <button data-m='lala' data-l="pinky">Click me</button>  

以及下面的Jquery代码,以检查是否有任何与按钮元素相关的CCD_ 1。

            if ($('button').data()) {
                console.log('there is data');
            }else{
                console.log('Theres no data')
            }  

但即使我去掉html数据属性,它也会记录CCD_ 2。

后来我发现了一个Jquery方法,它本身会告诉您,如果所选元素附带了data,该方法称为$.hasData()

所以我修改了我的程序如下:

if ($.hasData($('button'))) {
                    console.log('there is data');
                }else{
                    console.log('Theres no data')
                }

现在我的控制台中有there's no data。我不知道怎么了。

现在测试一下是否发生了这种情况,因为我是通过数据属性而不是Jquery data()方法附加数据的。我再次修改我的程序如下:

$('button').data({
                      'lala'   : '1',
                      'lala-1' :  '2'
                });
                if ($.hasData($('button'))) {
                    console.log('there is data');
                }else{
                    console.log('Theres no data')
                }

我的控制台中仍然有Theres no data

但如果我控制台日志如下:

console.log($('button').data());

我得到:

{ lala: "1", lala-1: "2", m: "lala", l: "pinky" }

现在,我只想让我的代码告诉我,当给定的元素有数据附加到它时(既有直接的html数据属性,也有Jquery data()属性),或者没有数据附加到。

如果有人能为我指明正确的方向,我将不胜感激。

谢谢。

亚历山大。

我的理解是JQuery的"hasData"接受一个元素,而不是元素的集合。

尝试:

var button = jQuery('button')[0];
jQuery.data( button, "testing", 123 );
if (jQuery.hasData(button)) {
  console.log('there is data');
} else {
  console.log('Theres no data')
}

来源:http://api.jquery.com/jquery.hasdata/

编辑:

经过测试,我得到了一些类似的结果,hasData没有拾取元素数据属性,所以这个小方法对我很有用:

HTML:

<button id="a" data-m='lala' data-l="pinky">Click me</button>  
<button id="b">Click me</button>  

Javascript:

var buttonA = jQuery('#a');
var buttonB = jQuery('#b');
if (Object.keys(buttonA.data()).length >0) {
    console.log("buttonA", "Has data");
} else {
    console.log("buttonA", "Has no data");
}
if (Object.keys(buttonB.data()).length >0) {
    console.log("buttonB", "Has data");
} else {
    console.log("buttonB", "Has no data");
}

输出:

buttonA Has data
buttonB Has no data

访问.data()将始终返回一个对象(甚至是一个空对象-data()0),因此在if条件下按原样使用它将始终生成true

$.hasData方法接受DOM元素,而不是jQuery对象,因此在您的情况下使用它的正确语法是:

if ($.hasData($('button')[0])) {
    console.log('there is data');
} else {
    console.log('Theres no data')
}

选择器后面的[0]用于检索jQuery对象中的第一个项——DOMElement本身。