使用 jquery .find() 遍历按类和存储属性选择元素

Traversing Using Jquery .find() to Select Element by Class & Store Prop

本文关键字:存储 属性 选择 元素 find jquery 遍历 使用      更新时间:2023-09-26

我正在尝试使用以下代码搜索元素"服务块"的后代,以查找具有类"title"的特定元素。我无法让 var 分配除"未定义"之外的任何内容。任何帮助将不胜感激 -

<div class="col-md-4">
        <div id="service-block" class="wp-block default grey-glow">
            <div class="figure">
                <img alt="..." src="~/images/services/nav-icon-white.jpg" class="img-responsive">
            </div>
            <div class="wp-block-body services-text">
                <h2 id="test" class="title">Lorem Ipsum <span class="heavy-header" style="color:#001990;">Lorem Ipsum</span> Lorem Ipsum</h2>
                <p>Lorem Ipsum.</p>
            </div>
        </div>
    </div> 
$("#service-block").hover(function () {
    var originalHeight = $(this).find('.title').prop("id");
});

这是你想要的吗?

$("#service-block").hover(function () {
    var $elem = $(this).find('.title');
    console.log("id of element: ", $elem.attr("id"));
    console.log("height of element: ", $elem.height()); //added due to your variable name
});

尝试将代码放在$(document).ready() 中。然后使用attr而不是prop

$(document).ready(function(){
   $("#service-block").hover(function(){
     var originalHeight = $(this).find('.title').attr("id");
   });
});