[英]Unable to access descendant of an HTML element using jQuery
I have a problem with getting a html()
value of child of a parent :D 我有一个获取父级的子级的
html()
值的问题:D
function voteup(e){ var count = $(e).parents('.item').children('.count'); console.log(count.html()); // undefined }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post_contain"> <img src="images/comments/dQ6dz.jpg" alt=""> </div> <div class="item"> <p class="post-meta"> <span href="/gag/agVzE1g" target="_blank"> <span class="count">5</span>points </span> </p> <div class="vote"> <ul class="btn-vote left"> <li class="badge-item-vote-up-li"> <a onclick="voteup(this)">Click me</a> </li> </ul> </div> </div>
In the function voteup(e)
, I need to get the value of the class 'count', but I don't retrieve the value with html()
在
voteup(e)
功能voteup(e)
,我需要获取“计数”类的值,但是我没有使用html()
检索该值。
children
only traverses a single level of the DOM tree - ie it won't find grandchildren. children
级仅遍历DOM树的单个级别-即找不到子级。
Instead, use closest
to find the .item
-- which finds the single nearest match, as opposed to parents
which can find multiple -- and find
to locate the child, since that will traverse arbitrarily deep HTML structures: 相反,请使用
closest
来查找.item
(查找单个最接近的匹配项,而不是找到多个.item
parents
,然后find
该子项的位置,因为那样会遍历任意深度的HTML结构:
function voteup(e){
var count = $(e).closest('.item').find('.count');
alert(count.html());
var actual = parseInt(count.html(), 10);
count.text(actual + 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.