简体   繁体   English

从jQuery中单击的父级获取价值

[英]Get value from clicked parent in jQuery

I have this code: 我有以下代码:

<div class="container">
     <div class="switchStatus btn-group" data-module="xxx">
          <a class="btn btn-primary">Active</a>
          <a class="btn btn-primary">Inactive</a>
     </div>
</div>

How can I get the data-module content ? 如何获取data-module内容?

Actually, my code looks like this but it doesn't work: 实际上,我的代码看起来像这样,但是不起作用:

$('.container').on('click', '.switchStatus a', function() {
    var module = $(this).data('module');
});

Thanks. 谢谢。

尝试

var module = $(this).parent().data('module');

Inside your click handler callback function, the this context will be bound to the <a> element that was clicked. 在您的点击处理程序回调函数中, this context将绑定到单击的<a>元素。 To get the parent, you can use the .closest() method with a selector. 要获取父项,可以将.closest()方法与选择器一起使用。 It could look like the following: 看起来可能如下所示:

$(this).closest("[data-module]").attr("data-module");

Use closest('.switchStatus'). 使用最近的('.switchStatus')。

jQuery sets the scope of the callback function to the element which is the subject of the callback jQuery将回调函数的范围设置为元素,该元素是回调的主题

So I guess that means the elements in the on selector parameter (.switchStatus a in this case) 所以我想这意味着on选择器参数(在这种情况下为.switchStatus a)中的元素

 $('.container').on('click', '.switchStatus a', function(event) { var module = $(this).closest('.switchStatus').data('module'); console.log('My name is ' + module) event.stopPropagation() // always good to stop event bubbles after you have used them. }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="switchStatus btn-group" data-module="Spartacus"> <a class="btn btn-primary">Active</a> <a class="btn btn-primary">Inactive</a> </div> </div> 

try this, whitout the node 'a' 试试这个,结束节点“ a”

$('.container').on('click', '.switchStatus', function() {
    var module = $(this).data('module');
    alert(module);
});

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

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