demand

You need to search for the corresponding value of the specified module, and then add the matching content to the background color and so on, just like the global search of the browser.

Train of thought

  • All contents of the currently specified region need to be fetched
  • Then find the search content in the selected content and add the corresponding background color
  • Finally, render the modified content onto the page

implementation

  • The contents of the corresponding module are retrieved using innerHTML
  • Write the corresponding regular expression to match the content of the search
  • Use string.prototype. replace to replace the matched content
  • Finally render to the page

Code implementation:

let wrap = document.querySelector('.wrap');
let innerHTML = wrap.innerHTML;
let reg = new RegExp(query, 'g');
innerHTML = innerHTML.replace(reg, '<span style="color: #000; background-color: #e3e4e5">' + query + '</span>');
wrap.innerHTML = innerHTML;
Copy the code

The specific implementation of the search implementation is completed, but there is a defect in the above code, is to replace the search content, the previous search content is still selected style, so the next to improve the function:

let preQuery = ' '; // What was searched last timelet wrapDom = ' '; // Search the dom element of the areafunction searchFn(dom, query) {
    let wrap = wrapDom || document.querySelector(dom);
    let innerHTML = wrap.innerHTML;
    if(! preQuery) {let preReg = new RegExp('<span style="color: #000; background-color: #e3e4e5">' + preQuery + '</span>'.'g');
        innerHTML = innerHTML.replace(preReg, preQuery);
    }
    if (query) {
        let reg = new RegExp(query, 'g');
        innerHTML = innerHTML.replace(reg, '<span style="color: #000; background-color: #e3e4e5">' + query + '</span>');
    }
    wrap.innerHTML = innerHTML;
    preQuery = query;
}
Copy the code

At this point, the search highlighting function is implemented.

Matters needing attention

  • The dom element in the search area can not use the title attribute, because when using the title attribute will also replace the corresponding title attribute content, page rendering will have problems, in fact, you can rewrite the regular expression matching rules, but the ability is limited, do not know how to write the regular expression excluding the title attribute

  • When writing with a framework such as Vue, all uE-related events and attributes are invalidated after the search because we are simply replacing the DOM, there are two solutions:

      1. After the search is complete, the VUE is instantiated again
    function resetVm() {
        vm.destroy()
        vm = new Vue({...})
    }
    Copy the code

    However, there is a problem with this. After the vue instance is re-instantiated, the search content is gone

      1. Instead of using VUE, you can implement the page using jQuery so that you don’t have event failures