我需要父div的data-offerId,但它无法正常工作。请建议我。
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的:
$('.clear-row').click(function(){
var offers = $('.clear-row').parent().attr('data-offerid');
console.log(offers);
});
答案 0 :(得分:3)
在处理程序中,您应该使用this
而不是重复选择器.clear-row
$('.clear-row').click(function(){
var offers = $(this).parent().attr('data-offerid');
console.log(offers);
});
您也可以使用data()
代替attr()
var offers = $(this).parent().data('offerid');
答案 1 :(得分:1)
在点击事件中使用this
,定位您点击的cleararrow
元素
$(this).parent().attr('data-offerid')
$('.clear-row').click(function() {
var offers = $(this).parent().attr('data-offerid');
console.log(offers);
});
工作示例
$('.clear-row').click(function() {
var offers = $(this).parent().attr('data-offerid');
console.log(offers);
});
&#13;
<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>
&#13;
答案 2 :(得分:1)
您可以使用jQuery
closest
方法[{3}}
$('.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>
如果您.attr
data attribute
.data(attribute-name);
,请使用data attribute
,而不是使用data-offerid
来获取{{1}}。
希望这对你有用。
答案 3 :(得分:0)
尝试这种方式:
$('.clear-row').click(function(){
var offers = $(this).parent().attr('data-offerid');
console.log(offers);
});
//OR
var offers = this.parentNode.getAttribute("data-offerid"); // plain javascript
帮助链接了解:parent