如何使用jquery实现外部ul的id?

knpiaxh1  于 2023-11-17  发布在  jQuery
关注(0)|答案(2)|浏览(153)

当我在浏览器中找到两个. html链接时,我想在jquery中实现外部ul的id(即-menu-right-2)。

var fullpath = window.location.pathname;
var filename = fullpath.replace(/^.*[\\\/]/, '');

var currentLink = $('a[href="' + filename + '"]');

var menuid = currentLink.parentsUntil('.menu-bar-right', 'ul').attr('id');
console.log(menuid);

个字符

kg7wmglp

kg7wmglp1#

parentUntil在所需div之前停止
你是说这个-最接近的在这里仍然工作得很好
一个分区中有多个UL

//var fullpath = window.location.pathname;
//var filename = fullpath.replace(/^.*[\\\/]/, '');

const getULIdFromFileName = filename => {
  var currentLink = $(`a[href="${filename}"]`);
  var menuid = currentLink.closest('ul[id^=menu-right').attr('id'); // closest UL with an ID that starts with menu-right 
  return menuid;
};

var filename = 'one.html'; // test for menu 1
console.log(getULIdFromFileName(filename));
filename = 'two.html'; // test for menu 2
console.log(getULIdFromFileName(filename));

个字符

2skhul33

2skhul332#

需要使用.closest()方法而不是.parentsUntil()来查找外部元素。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="menu-bar-right">
  <ul id="menu-right-2">
    <li class="nav-link">
      <a href="#">
        <span class="text nav-text">Yes</span>
      </a>
      <ul>
        <li class="nav-link">
          <a href="two.html">
            <span class="text nav-text">Two</span>
          </a>
        </li>
      </ul>
    </li>
    <li>Hello</li>
  </ul>
</div>
<script>
  var fullpath = window.location.pathname;
  var filename = fullpath.replace(/^.*[\\\/]/, '');

  var currentLink = $('a[href="' + filename + '"]');

  var menuid = currentLink.closest('.menu-bar-right').find('ul').attr('id');
  console.log(menuid);
</script>

字符串

相关问题