将动态值与逗号分隔的服饰价值进行比较

时间:2019-04-08 16:58:44

标签: javascript jquery

Please suggest how can I compare page Url Value inside all anchors element using Jquery.

<div class="sidebar">
    <a class="button" module="Users" page-actions="user/edit,user/create,user/list" href="user/index">User</a>
    <a class="button" module="Users" page-actions="" href="user/Demo">Demo</a>
    <a class="button" module="" page-actions="" href="/">Dashboard</a>
    </div>

假设我的页面网址是用户/编辑,我想访问page-actions属性等于页面网址的元素。

1 个答案:

答案 0 :(得分:1)

使用jQuery filter()并将页面操作解析为数组并与window.location.pathname进行比较

/** for demo only since demo url doesn't match */
var pageUrl ='http://example.com/user/edit';
var pagePath = new URL(pageUrl).pathname;


$('.sidebar a[page-actions]').filter(function(){
   var actionArray = $(this).attr('page-actions').split(',');  
   return actionArray.includes( pagePath.slice(1));
   // on live site use:
   // return actionArray.includes('/' + location.pathname.slice(1));   

}).css('color','red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
    <a class="button" module="Users" page-actions="user/edit,user/create,user/list" href="user/index">User</a>
    <a class="button" module="Users" page-actions="" href="user/Demo">Demo</a>
    <a class="button" module="" page-actions="" href="/">Dashboard</a>
    </div>