首页 > 解决方案 > 如何使用js/jquery访问标签的title属性

问题描述

标签: javascriptjqueryhtml

解决方案


您已经在 if 语句中获得了 title 的值,但是您'title'在分配中使用了该字符串。您需要$(this).attr('title')在两个地方都使用,或者更好地执行以下操作:

var title = $(this).attr('title');

if(title.includes("SOME")) {
    location.hash =  "#" + title;
    location.reload();
}

由于您使用的是 WordPress,jQuery.noConflict()可能正如 @charlietfl 在评论中提到的那样正在使用。因此,您可能需要用 替换所有$实例jQuery

jQuery(window).on('hashchange', function() {
    jQuery('.menu-item.menu-item-type-post_type.menu-item-object-page.current-menu-ancestor.current-menu-parent.current_page_parent.current_page_ancestor.menu-item-has-children.menu-item-top-level.menu-item-top-level-2.active-parent-item.dropdown_ul_available.current-menu-item')
        .on('click', 'a', function() {
            var title = jQuery(this).attr('title');

            if(title.includes("SOME")) {
                location.hash =  "#" + title;
                location.reload();
            }
         })
});

您也只在哈希更改时应用点击事件,您应该在每次页面加载时通过在文档准备好时添加来设置点击。请记住,如果可能的话,将下面的内容换成document您想要检查的特定容器是理想的,但由于可用的 HTML 有限,我保持简单。

jQuery(function() {
    jQuery('document').on('click', '.menu-item.menu-item-type-post_type.menu-item-object-page.current-menu-ancestor.current-menu-parent.current_page_parent.current_page_ancestor.menu-item-has-children.menu-item-top-level.menu-item-top-level-2.active-parent-item.dropdown_ul_available.current-menu-item > a', function() {
        if(Boolean(window.location.href.toString().includes("apple-uebersicht"))) 
        {
            if(jQuery(this).attr('title').includes("iphone")) {
                location.hash =  "#" + 'title';
                location.reload();
            }
        }
    })
});

推荐阅读