javascript - 获取由 PHP 生成的兄弟 div id

标签 javascript jquery html css

我有某种博客页面的 HTML 代码。下面 - 1 个帖子的代码及其 CSS 的高度削减。博客页面上会有很多帖子。我想通过单击“阅读更多”按钮查看特定页面的所有内容。 包含博客内容的 Div 具有通过 PHP 从数据库获取的动态 ID。

如何通过单击“阅读更多”按钮更改带有类“blog_article”的 div 的高度?

我想过使用 JS/Jquery,但无法获取“blog_article”div 的 ID。 或者也许有更好的方法来做到这一点?

<div class="blog_article_wrapper">  
  <div class="blog_article" id="<?php echo $id; ?>">    
    <!--Some content-->
   </div> 

    <div class="blog_article_read_more">
        <button onclick="blogReadMore()">Read More</button>
    </div>
 </div>

最佳答案

but cannot get id of "blog_article" div

为什么你不能?:

<button onclick="blogReadMore(<?php echo $id; ?>)">Read More</button>

或者,如果它是一个字符串:

<button onclick="blogReadMore('<?php echo $id; ?>')">Read More</button>

然后 blogReadMore() 有一个对 id 的引用:

function blogReadMore(id) {
    // use the id to identify the element and modify it however you want
}

相反,由于您标记了 jQuery,因此您可以从单击按钮开始遍历 DOM 以确定元素,而根本不需要任何 id。像这样:

$('.blog_article_read_more button').click(function () {
    var article = $(this).closest('.blog_article_wrapper').find('.blog_article');
    // do whatever you like with the article
});

关于javascript - 获取由 PHP 生成的兄弟 div id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232175/

相关文章:

jquery - 使用 basichttpbinding 调用 wcf webservice,无需 REST 或 JSON

javascript - jQuery 操作仅一次/自定义 URL

javascript - 扩展 HTML 元素

javascript - 如何使用 jQuery 将 div id 添加到 div?

javascript - 当未列出下拉选项时,用户可以手动输入自定义值

javascript - 将固定宽度的 div 定位在 float 的 "percent"div 旁边?

jquery - 元素中的响应 Bootstrap 轮播多列

javascript - 在 Javascript 中将下拉字段乘以文本字段

javascript - 如何从 Moment.JS 日期中删除时间?

php - 将 Javascript 放入 php 中