简体   繁体   English

在父元素中使用 jQuery 获取数据属性的值

[英]Get value of data attribute using jQuery in parent element

I have the following HTML code where onclick of .spot-info I want to get the value of data-test .我有以下 HTML 代码,其中onclick .spot-info我想获取data-test的值。

    <div class="spot" id="spot-1" data-test="12345">
        <div class="spot-main">
          <span>Test</span>
          <a href="#" class="spot-info">view</a>
        </div>
    </div>

    <div class="spot" id="spot-2" data-test="67891">
        <div class="spot-main">
          <span>Test</span>
          <a href="#" class="spot-info">view</a>
        </div>
    </div>

Please see my js attempt below:请在下面查看我的 js 尝试:

    $('.spot-info').click(function ( e ) {
        e.preventDefault();
        var test = $(this).parent().parent().data('data-test');
        console.log(test);
    });

This test is logging undefined in the console.此测试在控制台中记录undefined I thought this would work checking the parent of the parent of .spot-info .我认为这可以检查.spot-info的父级的父.spot-info

Also, is there way chaining a lot of parent(0) methods together rather than using jQuery.另外,有没有办法将许多parent(0)方法链接在一起而不是使用 jQuery。

try attr instead.尝试attr代替。 Also, try 'closest' instead of referring to the parent twice:另外,尝试 'closest' 而不是两次引用父级:

$('.spot-info').click(function ( e ) {
    e.preventDefault();
    var test = $(this).closest('.spot').attr('data-test');
    console.log(test);
});

Better if you could use closest() or parents() ,so instead of :如果您可以使用closest()parents()更好,所以而不是:

$(this).parent().parent().data('test');

Use :使用:

$(this).closest('.spot').data('test');
$(this).parents('.spot').data('test');

NOTE : The main problem come from .data('data-test');注意:主要问题来自.data('data-test'); When you use data() function you shouldn't add the string data- at the start.使用data()函数时,不应在开头添加字符串data-

Hopet his helps.希望他的帮助。


Working snippet工作片段

 $('.spot-info').click(function ( e ) { e.preventDefault(); var test = $(this).closest('.spot').data('test'); console.log(test); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="spot" id="spot-1" data-test="12345"> <div class="spot-main"> <span>Test</span> <a href="#" class="spot-info">view</a> </div> </div> <div class="spot" id="spot-2" data-test="67891"> <div class="spot-main"> <span>Test</span> <a href="#" class="spot-info">view</a> </div> </div>

Not sure - but I think it's this:不确定 - 但我认为是这样的:

$('.spot-info').click(function ( e ) {
    e.preventDefault();
    var test = $(this).parent().parent().data('test');
    console.log(test);
});

You don't need the data- prefix when fetching the data with .data()使用.data()获取数据时不需要data-前缀

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

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