我怎样才能得到h3的孩子li的照片呢?
<ul>
<li>
<h3> Element 1</h3>
<ul>
<li data-id="5">Element 1.1</li>
</ul>
</li>
</ul> 当我点击H3时,我怎样才能从孩子李那里得到data-id呢?我试着用JQuery.child()和JQuery.find(),但是没有用.
$(document).ready(function(){
$("h3").click(function(event){
var obj = event.target; //H3 here
//First attempt: 1º child = ul | 2º child = li
$(obj).child().child().attr('data-id');
//Second attempt:
$(obj).find("li").attr('data-id');
})
}) 有没有更好、更正确的方法来做到这一点?
发布于 2015-08-21 02:55:17
在您的示例中,您要针对的li是h3下一个兄弟姐妹的后代。
.find()用于查找调用元素的后代,但在本例中,目标元素不是h3的后代。
$(document).ready(function() {
$("h3").click(function(event) {
var id = $(this).next().find('li').data('id');
snippet.log('id: ' + id)
})
})<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<h3> Element 1</h3>
<ul>
<li data-id="5">Element 1.1</li>
</ul>
</li>
</ul>
发布于 2015-08-21 02:57:13
jQuery的.next()方法允许您查询DOM中匹配特定选择器的下一个元素。当您要寻找的元素不一定是后代时,这尤其有用。
因此,如果将单击事件处理程序中的h3元素引用为this,则可以执行$(this).next('li').data('id')。
旁白:.find()不需要再次查询元素;您只需在.next()步骤中查询li元素即可。
关于.next():https://api.jquery.com/next/的更多信息
发布于 2015-08-21 02:55:06
查找h3的下一个元素并得到ul,然后使用.find()查找它的子元素,使用以下代码:
$(document).ready(function(){
$("h3").click(function(event){
$(this).next().find("li").data('id');
})
}) https://stackoverflow.com/questions/32131654
复制相似问题