遍历div以匹配特定类与jquery

时间:2019-04-18 17:14:30

标签: javascript jquery wordpress

我要执行的操作是,如果特定div组中的div与主体类ID号(例如,“。post-123”-ID号为“ 123”)具有相同的类ID号(例如“ .postid-123”),然后向该div添加一个具有相同ID号的新类。

在我的代码中,所有内容似乎都运行正确,只是没有循环遍历该组中的所有div,而只是将新类追加到该组中的第一个div。

jQuery / JS:

<script>
jQuery(document).ready(function($) {
    var current_post_id = get_current_post_id();
    var current_project_id = get_current_project_id();

    function get_current_post_id() {
        var body_class = $('body.single-project');
        var post_id = '';

        if(body_class) {
            var classList = body_class.attr('class').split(/\s+/);
            $.each(classList, function(index, item) {
                if (item.indexOf('postid') >= 0) {
                    var item_arr = item.split('-');
                    post_id = item_arr[item_arr.length -1];
                    return false;
                }
            });
        }
        return post_id;
    }

    function get_current_project_id() {
        var project = $('.et_pb_portfolio .et_pb_portfolio_item');
        var project_id = '';

        if(project) {
            var classList = project.attr('class').split(/\s+/);
            $.each(classList, function(index, item) {
                if (item.indexOf('post') >= 0) {
                    var item_arr = item.split('-');
                    project_id = item_arr[item_arr.length -1];
                    return false;
                }
            });
        }
        return project_id;
    }

    if (current_post_id == current_project_id) {
            $('.et_pb_portfolio #post-' + current_project_id).addClass('current-project');
        }
    console.log('project id is: ' + current_project_id);
    console.log('page id is: ' + current_post_id);
});
</script>

HTML(只是页面上所需内容的一小段):

<body class="project-template-default single single-project postid-688 logged-in admin-bar has-stick chrome windows et_button_icon_visible et_button_custom_icon et_pb_button_helper_class et_transparent_nav et_fullwidth_nav et_fullwidth_secondary_nav et_non_fixed_nav et_show_nav et_cover_background et_secondary_nav_enabled et_secondary_nav_two_panels et_pb_gutter et_pb_gutters3 et_primary_nav_dropdown_animation_fade et_secondary_nav_dropdown_animation_fade et_pb_footer_columns4 et_header_style_left et_pb_pagebuilder_layout et_smooth_scroll et_right_sidebar et_divi_theme et-db et_minified_js et_minified_css customize-support"<div class="et_pb_module et_pb_portfolio et_pb_portfolio_0  et_pb_bg_layout_light">
    <div class="et_pb_ajax_pagination_container">
        <div id="post-708" class="post-708 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/finite-element-analysis/" title="Finite Element Analysis">Finite Element Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-702" class="post-702 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/refinery-project-water-wash-system/" title="Refinery Project – Water Wash System">Refinery Project – Water Wash System</a>
            </h3>   
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-695" class="post-695 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/marcellus-compression-station/" title="Marcellus Compression Station">Marcellus Compression Station</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-693" class="post-693 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/houston-ship-channel-tank-farm-expansion/" title="Houston Ship Channel – Tank Farm Expansion">Houston Ship Channel – Tank Farm Expansion</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-688" class="post-688 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/process-safety-management-pha-lopa-analysis/" title="Process Safety Management – PHA &amp; LOPA Analysis">Process Safety Management – PHA &amp; LOPA Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
    </div>
</div>
</body>

2 个答案:

答案 0 :(得分:0)

这是一种更简单的香草方式。

const getCurrentProjectId = () => { 
  let postId = Array.from(document.querySelector('body').classList).find(cls => cls.indexOf('postid-') > -1).split('-')[1];
  
  return `post-${postId}`;
  
}

console.log(getCurrentProjectId());

document.addEventListener('DOMContentLoaded', () => {
  let currentProject = getCurrentProjectId();
  document.querySelectorAll('.project').forEach(proj => {
    if(proj.classList.contains(currentProject)) proj.classList.add('current-project');
  });
});
.current-project {
  border: 2px solid red;
}
<body class="project-template-default single single-project postid-688 logged-in admin-bar has-stick chrome windows et_button_icon_visible et_button_custom_icon et_pb_button_helper_class et_transparent_nav et_fullwidth_nav et_fullwidth_secondary_nav et_non_fixed_nav et_show_nav et_cover_background et_secondary_nav_enabled et_secondary_nav_two_panels et_pb_gutter et_pb_gutters3 et_primary_nav_dropdown_animation_fade et_secondary_nav_dropdown_animation_fade et_pb_footer_columns4 et_header_style_left et_pb_pagebuilder_layout et_smooth_scroll et_right_sidebar et_divi_theme et-db et_minified_js et_minified_css customize-support"<div class="et_pb_module et_pb_portfolio et_pb_portfolio_0  et_pb_bg_layout_light">
    <div class="et_pb_ajax_pagination_container">
        <div id="post-708" class="post-708 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/finite-element-analysis/" title="Finite Element Analysis">Finite Element Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-702" class="post-702 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/refinery-project-water-wash-system/" title="Refinery Project – Water Wash System">Refinery Project – Water Wash System</a>
            </h3>   
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-695" class="post-695 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/marcellus-compression-station/" title="Marcellus Compression Station">Marcellus Compression Station</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-693" class="post-693 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/houston-ship-channel-tank-farm-expansion/" title="Houston Ship Channel – Tank Farm Expansion">Houston Ship Channel – Tank Farm Expansion</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-688" class="post-688 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/process-safety-management-pha-lopa-analysis/" title="Process Safety Management – PHA &amp; LOPA Analysis">Process Safety Management – PHA &amp; LOPA Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
    </div>
</div>
</body>

以下是使用find的选项(假设只有一个帖子):

const getCurrentProjectId = () => `post-${Array.from(document.querySelector('body')
                                               .classList)
                                               .find(cls => cls.indexOf('postid-') > -1)
                                               .split('-')[1]}`;

console.log(getCurrentProjectId());

document.addEventListener('DOMContentLoaded', () => {
  let currentProject = getCurrentProjectId();
  Array.from(document.querySelectorAll('.project'))
       .find(proj => proj.classList.contains(currentProject))                                            .classList.add('current-project');
});
.current-project {
  border: 2px solid red;
}
<body class="project-template-default single single-project postid-688 logged-in admin-bar has-stick chrome windows et_button_icon_visible et_button_custom_icon et_pb_button_helper_class et_transparent_nav et_fullwidth_nav et_fullwidth_secondary_nav et_non_fixed_nav et_show_nav et_cover_background et_secondary_nav_enabled et_secondary_nav_two_panels et_pb_gutter et_pb_gutters3 et_primary_nav_dropdown_animation_fade et_secondary_nav_dropdown_animation_fade et_pb_footer_columns4 et_header_style_left et_pb_pagebuilder_layout et_smooth_scroll et_right_sidebar et_divi_theme et-db et_minified_js et_minified_css customize-support"<div class="et_pb_module et_pb_portfolio et_pb_portfolio_0  et_pb_bg_layout_light">
    <div class="et_pb_ajax_pagination_container">
        <div id="post-708" class="post-708 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/finite-element-analysis/" title="Finite Element Analysis">Finite Element Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-702" class="post-702 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/refinery-project-water-wash-system/" title="Refinery Project – Water Wash System">Refinery Project – Water Wash System</a>
            </h3>   
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-695" class="post-695 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/marcellus-compression-station/" title="Marcellus Compression Station">Marcellus Compression Station</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-693" class="post-693 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/houston-ship-channel-tank-farm-expansion/" title="Houston Ship Channel – Tank Farm Expansion">Houston Ship Channel – Tank Farm Expansion</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-688" class="post-688 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/process-safety-management-pha-lopa-analysis/" title="Process Safety Management – PHA &amp; LOPA Analysis">Process Safety Management – PHA &amp; LOPA Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
    </div>
</div>
</body>

这是一个考虑ID周围BenM评论的选项

const getCurrentProjectId = () => `post-${Array.from(document.querySelector('body')
                                               .classList)
                                               .find(cls => cls.indexOf('postid-') > -1)
                                               .split('-')[1]}`;

console.log(getCurrentProjectId());

document.addEventListener('DOMContentLoaded', () => {  
  document.querySelector(`#${getCurrentProjectId()}`).classList.add('current-project');
});
.current-project {
  border: 2px solid red;
}
<body class="project-template-default single single-project postid-688 logged-in admin-bar has-stick chrome windows et_button_icon_visible et_button_custom_icon et_pb_button_helper_class et_transparent_nav et_fullwidth_nav et_fullwidth_secondary_nav et_non_fixed_nav et_show_nav et_cover_background et_secondary_nav_enabled et_secondary_nav_two_panels et_pb_gutter et_pb_gutters3 et_primary_nav_dropdown_animation_fade et_secondary_nav_dropdown_animation_fade et_pb_footer_columns4 et_header_style_left et_pb_pagebuilder_layout et_smooth_scroll et_right_sidebar et_divi_theme et-db et_minified_js et_minified_css customize-support"<div class="et_pb_module et_pb_portfolio et_pb_portfolio_0  et_pb_bg_layout_light">
    <div class="et_pb_ajax_pagination_container">
        <div id="post-708" class="post-708 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/finite-element-analysis/" title="Finite Element Analysis">Finite Element Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-702" class="post-702 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/refinery-project-water-wash-system/" title="Refinery Project – Water Wash System">Refinery Project – Water Wash System</a>
            </h3>   
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-695" class="post-695 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/marcellus-compression-station/" title="Marcellus Compression Station">Marcellus Compression Station</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-693" class="post-693 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/houston-ship-channel-tank-farm-expansion/" title="Houston Ship Channel – Tank Farm Expansion">Houston Ship Channel – Tank Farm Expansion</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
        <div id="post-688" class="post-688 project type-project status-publish hentry et_pb_post et_pb_portfolio_item">
            <h3 class="et_pb_module_header">
                <a href="/project/process-safety-management-pha-lopa-analysis/" title="Process Safety Management – PHA &amp; LOPA Analysis">Process Safety Management – PHA &amp; LOPA Analysis</a>
            </h3>
        </div><!-- .et_pb_portfolio_item -->
    </div>
</div>
</body>

答案 1 :(得分:0)

为什么要遍历所有div元素才能做到这一点?

由于ID属性始终是唯一的,因此您可以从body类中提取ID,然后选择相关元素:

if( $('body').hasClass('single-project') )
{
    var postID = /(postid-)[0-9]+/gm.exec($('body').attr('class'))[0].replace('postid-', '');

    $('#post-' + postID).addClass('current-project');
}