简体   繁体   English

如何在jQuery中获取父div属性值?

[英]how to get parent div attribute values in jquery?

I need data-offerId of parent div but it's not working properly. 我需要父div的data-offerId,但无法正常工作。 Please suggest me. 请给我建议。

HTML HTML

<div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>
<div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>

Jquery: jQuery的:

 $('.clear-row').click(function(){
     var offers = $('.clear-row').parent().attr('data-offerid');
     console.log(offers);
 });

Inside the handler, you should be using this not repeating the selector .clear-row 在处理程序内部,您应该使用this而不重复选择器.clear-row

$('.clear-row').click(function(){
   var offers = $(this).parent().attr('data-offerid');
   console.log(offers);
});

You can also use data() instead of attr() 您也可以使用data()代替attr()

var offers = $(this).parent().data('offerid');

Use this inside your click event, to target the cleararrow element your clicked on 在您的click事件中使用this ,以定位您单击的cleararrow元素

$(this).parent().attr('data-offerid')

$('.clear-row').click(function() {
  var offers = $(this).parent().attr('data-offerid');
  console.log(offers);
});

Working example 工作实例

 $('.clear-row').click(function() { var offers = $(this).parent().attr('data-offerid'); console.log(offers); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row">clear</span></div> <div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row">clear</span></div> 

Here you go with one more way using jQuery closest method https://jsfiddle.net/464g5hzq/ 在这里,您可以使用jQuery closest方法https://jsfiddle.net/464g5hzq/

 $('.clear-row').click(function(){ var offers = $(this).closest('div.rows').data('offerid'); console.log(offers); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div> <div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div> 

Instead of using .attr to get the data attribute , please use .data(attribute-name); 请勿使用.attr来获取data attribute ,而应使用.data(attribute-name); if you have data attribute like data-offerid . 如果您具有data-offerid类的data-offerid data attribute

Hope this will be useful to you. 希望这对您有用。

Try this way: 尝试这种方式:

$('.clear-row').click(function(){
    var offers = $(this).parent().attr('data-offerid');
    console.log(offers);
});

//OR

var offers = this.parentNode.getAttribute("data-offerid");   // plain javascript

Helper Link to understand: parent 帮手链接了解: 家长

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

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