简体   繁体   English

jQuery获取返回未定义的数据属性

[英]JQuery getting a data attribute returning undefined

I am trying to get the value of data-scanID from the clicked tag and store it inside a variable called scanID but the alert comes up undefined. 我正在尝试从单击的标记中获取data-scanID的值,并将其存储在名为scanID的变量中,但警报未定义。

$("#trucklist").click(function(event) {
    var scanID=$(event.target).data("scanID");
    alert(scanID);
});

The html looks something like this: html看起来像这样:

<ul id="trucklist">
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
</ul>

You are targetting ul . 您的目标是ul Try this: 尝试这个:

$("#trucklist > li").click(function(event) {
    var scanID=$(this).data("scanID");
    alert(scanID);
});

The above will target the trucklist 's child li and alert you its data . 上面的内容将针对trucklist的孩子li并提醒您其data

Also, I would suggest you to wrap the attribute's value within quotes. 另外,我建议您将属性的值括在引号中。

Also, data attributes cannot contain capital letters. 另外,数据属性不能包含大写字母。 So change them or it will not work. 因此,请更改它们,否则将不起作用。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM