为了账号安全,请及时绑定邮箱和手机立即绑定

遍历div以将特定类与jquery匹配

遍历div以将特定类与jquery匹配

胡子哥哥 2021-04-27 12:10:21
我要尝试做的是,如果特定div组中的div与主体类ID号(例如,)具有相同的类ID号(例如,“。post-123”-ID号是“ 123”)。 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>
查看完整描述

2 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

这是执行此操作的一种更简单的原始方法。

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>

这是一个考虑到BenM对ID的评论的选项

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>


查看完整回答
反对 回复 2021-05-06
?
跃然一笑

TA贡献1826条经验 获得超6个赞

为什么您需要遍历所有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');

}


查看完整回答
反对 回复 2021-05-06
  • 2 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信