我正在尝试获取下一个div的数据键。但它给了我'未定义'
这是html代码
<div class="sort-arrows"><span class="fa fa-arrow-up" id="sort-up"></span><span class="fa fa-arrow-down" id="sort-down"></span></div>
<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
<h3 class="bg-primary">Title</h3>
</div>
演示 - https://jsfiddle.net/v8wkt0yL/
非常感谢任何帮助。
答案 0 :(得分:1)
点击箭头时,你感兴趣的东西就是箭头的父母兄弟。
$("body").on('click tap', '.sort-arrows .fa-arrow-down', function(e) {
e.preventDefault();
var $flow = $(this).parent().siblings("div.flow-content:first");
// ======================
// also works but more brittle
// ======================
// var $flow = $(this).parent().next();
// ======================
console.log($flow.data("key"));
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />
<div class="sort-arrows">
<span class="fa fa-arrow-up" id="sort-up"></span>
<span class="fa fa-arrow-down" id="sort-down"</span>
</div>
<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
<h3 class="bg-primary">Title</h3>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:1)
$("body").on('click tap', '.sort-arrows .fa-arrow-down', function(e) {
e.preventDefault();
var elem = $(this).parent().attr("class");
var data = $("." + elem).next(".flow-content").attr("data-key");
alert(data);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />
<div class="sort-arrows"><span class="fa fa-arrow-up" id="sort-up"></span><span class="fa fa-arrow-down" id="sort-down"></span></div>
<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
<h3 class="bg-primary">Title</h3>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 2 :(得分:-1)
$(this).attr("data-key")
或
$(this).data("key")