简体   繁体   English

通过ID动态选择嵌套元素

[英]Dynamically selecting nested elements by ID

I never fully understood JQuery selectors. 我从不完全了解JQuery选择器。 How to go up/down or in/out nested elements which are dynamically created and are identified only by a unique id. 如何上/下或进/出嵌套元素,这些元素是动态创建的并且仅由唯一ID标识。 For example now I have this: 例如现在我有这个:

<div class="item white" id="871" name="871">
    <span class="twitter"><a href="php/tweet.php">Tweet</a></span>        
    <div class="topleft">
         <ul class="ribbon pinky">
             <li class="date_header"></li>
             <li class="date_number"></li>
             <li class="date_footer"></li>                          
         </ul>
    </div>
    <div class="bottomleft">
         <ul class="links">
             <li><a href=""><img src="" alt=""/></a></li>
             <li><a href="mailto:"><img src="" alt=""/></a></li>
         </ul>
    </div>
    <div class="topright">
        <ul class="white_box_content">
             <li class="picture"><img class="image" src="" alt="" /></li>
             <li class="title"></li>
             <li class="subtitle"></li> 
             <li class="description"></li>
         </ul>
    </div>
    <div class="item_footer">
    <div class="line"></div>
         <ul class="footer_content">
               <li class="place"></li>
               <li class="contacts"></li>
         </ul>
    </div>
</div>

My web page is built by a number of these HTML 'blocks'. 我的网页由许多这些HTML“块”构建。 Now i would like to get the ID and the value of the 'title' class using JQuery as I want to pass them to a PHP file using Ajax. 现在,我想使用JQuery来获取'title'类的ID和值,因为我想使用Ajax将它们传递给PHP文件。

 $(".twitter").click(function(event){ 
      event.preventDefault();
           var i = $(this).closest('.item').attr('id');
           var t = TITLE ??
           $.get("php/tweet.php", { id: i, title: t } );
           return false;
 });

I managed to get the ID only using: 我设法使用以下方法获取ID:

$(this).closest('.item').attr('id');

Now, how to I get the .TITLE class? 现在,如何获取.TITLE类? How do I use the ID to select the correct .TITLE? 如何使用ID选择正确的.TITLE? When I click the link I would like to pass the .title value to tweet.php. 当我单击链接时,我想将.title值传递给tweet.php。

Try find(): 尝试find():

$(this).closest('.item').find('.title').html();

http://api.jquery.com/find/ http://api.jquery.com/find/

http://api.jquery.com/class-selector/ http://api.jquery.com/class-selector/

That code gets the html contents of the element with class title inside an element with class item. 该代码获取具有类标题的元素内具有类标题的元素的html内容。

Once you get the ID, you can use it to get the .title div: 一旦获得ID,就可以使用它来获取.title div:

var t = $("#"+i+" .topright .title");

And if you want the title inside the div: 如果您想在div内添加标题:

var t = $("#"+i+" .topright .title").text();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM