Adding attributes to an anchor in Wordpress

泄露秘密 提交于 2019-12-06 07:45:45

There's a few reasons your script isn't working. Here's some suggestions, and some code that is tested to apply the attributes you are after to the links in the navigation:

  1. You might consider moving the ready away from each separate call to a function that contains all of the calls rather than for each call separately. (I have done that below for you).
  2. .page_item is not a link, it is an li element. Also note that this is ONLY the navigation links - it will not apply to any links in the content of the pages/posts.
  3. Jquery in WordPress is not always safe to run using $. By wrapping the calls in a document ready called with jQuery, you can still use $ within the function to call the jQuery functions.

    jQuery(function($) {
        $('.page_item a').each(function(){
            $(this).attr('data-transition', 'pop');
            $(this).attr('data-icon', 'arrow-r');
            $(this).attr('data-iconpos', 'left');
            $(this).attr('data-role', 'button');
        });
    });
    

EDIT :
Per the excellent comments by @Jasper the much better way to do this would be:

jQuery(function($) {
    $('.page_item a').attr({ 'data-transition' : 'pop', 
            'data-icon' : 'arrow-r', 
            'data-iconpos' : 'left', 
            'data-role' : 'button' });
    });

$.ready() is a special event for document loading, and only works on the document. You need to iterate through the items using $.each() instead.

$(document).ready(function(){
  $('.page_item').each(function() {
    $(this).attr('data-transition', 'pop');
    $(this).attr('data-icon', 'arrow-r');
    $(this).attr('data-iconpos', 'left');
    $(this).attr('data-role', 'button');
  });
});
jQuery(function() {
    jQuery('li.page_item a').each(function () {
        jQuery(this).attr({
            'data-transition': 'pop',
            'data-icon': 'arrow-r',
            'data-iconpos': 'left',
            'data-role': 'button'
        });
    });
});

or just

jQuery(function () {
    jQuery('li.page_item a').attr({
        'data-transition': 'pop',
        'data-icon': 'arrow-r',
        'data-iconpos': 'left',
        'data-role': 'button'
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!