[英]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. 希望这对您有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.