所以我在'li'之后添加span,当点击时我想获得最接近的'li'及其子'img'的数据值。出于某种原因,我未定义。
<div id="mi-slider" class="mi-slider">
<ul>
<li><a href="#"><img data-value="1" src="images/1.jpg" alt="img01"><h4>Boots</h4></a></li>
<li><a href="#"><img data-value="2" src="images/2.jpg" alt="img02"><h4>Oxfords</h4></a></li>
<li><a href="#"><img data-value="3" src="images/3.jpg" alt="img03"><h4>Loafers</h4></a></li>
</ul>
</div>
$(".mi-slider ul:first-child li").after('<span class="aff_delete">X</span>');
// delete product
$( ".aff_delete" ).click( function() {
// product id
var id = $(this).closest('li').children('img').attr('data-value');
alert(id);
});
See here 单击x时,您将获得该值。
答案 0 :(得分:2)
您需要使用prev()
,因为span
是兄弟find
,因为img
是嵌套儿童
$(".mi-slider ul:first-child li").after('<span class="aff_delete">X</span>');
// delete product
$(".aff_delete").click(function() {
// product id
var id = $(this).prev('li').find('img').attr('data-value');
alert(id);
});
&#13;
.aff_delete {
color: red;
font-weight: bold;
cursor: pointer;
font-size: 18px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="mi-slider" class="mi-slider">
<ul>
<li>
<a href="#">
<img data-value="1" src="images/1.jpg" alt="img01">
<h4>Boots</h4>
</a>
</li>
<li>
<a href="#">
<img data-value="2" src="images/2.jpg" alt="img02">
<h4>Oxfords</h4>
</a>
</li>
<li>
<a href="#">
<img data-value="3" src="images/3.jpg" alt="img03">
<h4>Loafers</h4>
</a>
</li>
</ul>
</div>
&#13;