简体   繁体   English

使用冒号分隔的参数合并 URL

[英]Merge URLs with colon-separated parameters

i'm trying to write a script to update URLs with colon-separated parameters in JS, because page content is loaded via AJAX.我正在尝试编写一个脚本来更新 JS 中以冒号分隔的参数的 URL,因为页面内容是通过 AJAX 加载的。

The Document structure is like this:文档结构是这样的:

Format:
<div class="filter" id="formats">
  <a class="active" href="https://cdpn.io/page/">All</a>
  <a href="https://cdpn.io/page/format:foo">Foo</a>
  <a href="https://cdpn.io/page/format:bar">Bar</a>
  <a href="https://cdpn.io/page/format:baz">Baz</a>
<div>

<br>

Topic:
<div class="filter" id="topics">
  <a class="active" href="https://cdpn.io/page/">All</a>
  <a href="https://cdpn.io/page/topic:foo">Foo</a>
  <a href="https://cdpn.io/page/topic:bar">Bar</a>
  <a href="https://cdpn.io/page/topic:baz">Baz</a>
</div>
  
<br>
  
Sort By:
<div class="filter" id="sort">
  <a href="https://cdpn.io/page/sort:topic-asc">Topic Asc</a>
  <a href="https://cdpn.io/page/sort:topic-desc">Topic Desc</a>
  <br>
  <a href="https://cdpn.io/page/sort:title-asc">Title Asc</a>
  <a href="https://cdpn.io/page/sort:title-desc">Title Desc</a>
</div>

  <br>
  Url loaded:
<div id="content">
  https://cdpn.io/page
</div>

only #content is updated by the AJAX library, all links need to be changed "manually".只有#content由 AJAX 库更新,所有链接都需要“手动”更改。

For example: if I click on a filter-link like https://example.com/page/topic:foo , page content is refreshed, but all filters need to be updated: https://example.com/page/format:bar should become https://example.com/page/topic:foo/format:bar etc. Whenever any of the filters is clicked, existing parameters need to be overwritten or appended if they're not there yet, and removed when they don't exist.例如:如果我点击像https://example.com/page/topic:foo这样的过滤器链接,页面内容会刷新,但所有过滤器都需要更新: https://example.com/page/format:bar应变为https://example.com/page/topic:foo/format:bar等。每当单击任何过滤器时,如果现有参数尚不存在,则需要覆盖或附加它们,并在他们不存在。

I thought I had it figured out by mapping all params in an array of objects, then merging using a snippet I found on StackOverflow and returning the string, but there seems to be an error in my logic and I can't put my finger on it…我以为我已经通过映射对象数组中的所有参数来解决它,然后使用我在 StackOverflow 上找到的片段进行合并并返回字符串,但我的逻辑似乎有错误,我无法确定它…

const mergeByProperty = (target, source, prop) => {
  source.forEach(sourceElement => {
    let targetElement = target.find(targetElement => {
      return sourceElement[prop] === targetElement[prop];
    })
    targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
  })
}

for (el of document.querySelectorAll('a')) {
  el.addEventListener('click', (e) => {
    e.preventDefault();
    loadNewContent(e.target);
  })
}

const loadNewContent = (target) => {
  document.querySelector('#content').innerText = target 
  // this is where page content is fetched & appended etc, then:
  updateLinks(target)
}

const updateLinks = (trigger) => {
  document.querySelectorAll('a').forEach(linkToUpdate => {
    linkToUpdate.href = mergeURLs(linkToUpdate.href, trigger.href);
  })
}

function mergeURLs(url1, url2) {
  let params1 = getParams(url1)
  let params2 = getParams(url2)
  mergeByProperty(params1, params2, 'param')
  let newParamString = params1.map(s => `${s.param}:${s.value}`).join('/');
  return `${window.location.origin}/page/${newParamString}`;
}

Here's a link to a codepen where I tried around.这是我尝试过的codepen的链接。

https://codepen.io/moevbiz/pen/OJRNNex?editors=0011 https://codepen.io/moevbiz/pen/OJRNNex?editors=0011

Thankful for any hints or suggestions…感谢任何提示或建议...

Solution: Instead of creating an object from URL parameters and trying to merge them, I'm using regex to replace existing parameters.解决方案:我没有从 URL 参数创建 object 并尝试合并它们,而是使用正则表达式替换现有参数。

Codepen: https://codepen.io/moevbiz/pen/gOwrKYO?editors=0011代码笔: https://codepen.io/moevbiz/pen/gOwrKYO?editors=0011

Links get data attributes like the following:链接获取如下数据属性:

<a data-param="format" data-param-string="format:foo" href="https://cdpn.io/page/format:foo">Foo</a>

the working code:工作代码:

for (el of document.querySelectorAll('a')) {
  el.addEventListener('click', (e) => {
    e.preventDefault();
    loadNewContent(e.target);
  })
}

const loadNewContent = (trigger) => {
  document.querySelector('#content').innerText = trigger;
  updateLinks(trigger)
}

const updateLinks = (trigger) => {
  document.querySelectorAll('a').forEach(linkToUpdate => {
    if (linkToUpdate.dataset.param != trigger.dataset.param) { // only update links that don't belong to the same group of elements
      linkToUpdate.href = merge(linkToUpdate.href, trigger.dataset.param, trigger.dataset.paramString); 
    }
  })
}

const merge = (url, param, paramString) => {
  let newUrl;
  let regex = new RegExp(`(${param}:[^\/]*)`, "g")

  function replaceParam(url, newParamString) {
    return url.replace(regex, newParamString)
  }
  
  if (url.includes(`${param}:`)) { // replace param if it already exists, else append it to the href
    newUrl = replaceParam(url, paramString)
  } else {
    newUrl = url.concat('/' + paramString)
  }
  return newUrl.replace(/([^:])(\/\/+)/g, '$1/'); // remove double slashes except after https://
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM