Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当用户键入单词时,如何将每个匹配的字母加粗?_Javascript_Html - Fatal编程技术网

Javascript 当用户键入单词时,如何将每个匹配的字母加粗?

Javascript 当用户键入单词时,如何将每个匹配的字母加粗?,javascript,html,Javascript,Html,这是我的HTML的一部分,足以看出问题所在,还有JavaScript代码,当用户的输入与我的标题或正文匹配时,我不知道如何将每个字母/单词加粗。当用户输入一些文本时,我使用JSON API holder获取/posts。如果有人能完成我的boldSearchedWord()函数,非常感谢 HTML: JavaScript: // Ataching event listener let myInput = document.querySelector('.search'); //setup b

这是我的HTML的一部分,足以看出问题所在,还有JavaScript代码,当用户的输入与我的标题或正文匹配时,我不知道如何将每个字母/单词加粗。当用户输入一些文本时,我使用JSON API holder获取/posts。如果有人能完成我的boldSearchedWord()函数,非常感谢

HTML:


JavaScript:

// Ataching event listener
let myInput = document.querySelector('.search');
//setup before functions
let typingTimer;
let doneTypingInterval = 500;
let searchElement = document.querySelector('.items');
let sorryItemElement = '<div class="sorry-wrapper"><i class="fas fa-truck-loading"></i><a href="#" class="sorry-msg">Sorry, we couldn\'t find anything :(</a><div>';
let loadingItemElement = '<div class="loading"><i class="fas fa-spinner"></i> Loading...</div>';
// keyup event would be better, but it doesn't recognize backspace because backspace it's not printable key
myInput.addEventListener('keydown', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(searchBodyTitle, doneTypingInterval);
    }
});


async function searchBodyTitle() {
    const query = myInput.value;
    // early return
    if (query === '') {
        clearItems();
        return;
    }

    try {
        startLoading();
        const result = await fetch(`https://jsonplaceholder.typicode.com/posts?q=${query}`);
        const data = await result.json();
        const posts = data.map(post => {
            return {
                title: post.title,
                body: post.body
            }
        });
        finishLoading();
        if (posts.length === 0) {
            searchElement.innerHTML += sorryItemElement;
        } else {
            posts.forEach(post => {
                let slicedTitle = post.title.slice(0, 30);
                let slicedBody = `${post.body.slice(0, 50)} ...`;
                newElement(slicedTitle, slicedBody);
            });
        }
        return data;
    } catch (error) {
        finishLoading();
        console.log(error);
    }
}

function clearItems() {
    searchElement.innerHTML = '';
}

function newElement(title, body) {
    let newElement = `<a href="#" class="item-options"><span class="dropdown-title">${title}</span><span class="dropdown-body">${body}</span></a>`;
    searchElement.innerHTML += newElement;
}

function startLoading() {
    clearItems();
    searchElement.innerHTML += loadingItemElement;
}

function finishLoading() {
    clearItems();
}

function boldSearchedWord() {
    let titles = document.querySelectorAll('.dropdown-title');
   
}
//Ataching事件侦听器
让myInput=document.querySelector('.search');
//功能前设置
让打字计时器;
设doneTypingInterval=500;
让searchElement=document.querySelector('.items');
让sorryItemElement='';
让loadingItemElement='Loading…';
//keyup事件会更好,但它不能识别backspace,因为backspace它不是可打印的键
myInput.addEventListener('keydown',()=>{
clearTimeout(键入计时器);
if(myInput.value){
typingTimer=setTimeout(searchBodyTitle,doneTypingInterval);
}
});
异步函数searchBodyTitle(){
const query=myInput.value;
//提前返回
如果(查询==''){
clearItems();
返回;
}
试一试{
惊人的负荷();
const result=等待获取(`https://jsonplaceholder.typicode.com/posts?q=${query}`);
const data=wait result.json();
const posts=data.map(post=>{
返回{
标题:post.title,
body:post.body
}
});
完成加载();
如果(posts.length==0){
searchElement.innerHTML+=sorryItemElement;
}否则{
posts.forEach(post=>{
设slicedTitle=post.title.slice(0,30);
让slicedBody=`${post.body.slice(0,50)}…`;
新元素(slicedTitle、slicedBody);
});
}
返回数据;
}捕获(错误){
完成加载();
console.log(错误);
}
}
函数clearItems(){
searchElement.innerHTML='';
}
函数新元素(标题、正文){
让newElement=`;
searchElement.innerHTML+=新元素;
}
函数惊人加载(){
clearItems();
searchElement.innerHTML+=loadingItemElement;
}
函数finishLoading(){
clearItems();
}
函数boldSearchedWord(){
让titles=document.querySelectorAll('.dropdown title');
}

您可以使用下面的代码

它使用匹配值中的
进行替换。 最后有一个演示

函数escapeRegex(字符串){
返回字符串.replace(/[-\/\^$*+.()|[\]{}]/g,'\\$&');
}
函数boldSearchedWord(文本,搜索){
const escapedSearch=escapeRegex(搜索);
//\\b:仅查找以搜索值开头的单词
//g:找到所有单词,而不仅仅是第一个单词
//m:在多行中查找
//i:忽略区分大小写
const regexpression=new RegExp('\\b('+escapedSearch+')\\b','gmi');
设additionalIndexValue=0;
让newText=文本;
while((match=regexpression.exec(text))!==null){
常量boldMatch=''+匹配[0]+'';
常量matchStart=match.index+additionalIndexValue;
const matchEnd=regexpression.lastIndex+additionalIndexValue;
newText=newText.substr(0,匹配开始)+boldMatch+newText.substr(匹配结束);
//每次匹配后,在文本中搜索的字符串周围添加一个“”HTML元素
//然后我们需要将附加值添加到索引中,以进行正确的替换
附加指数X值+=7;
}
返回新文本;
}
学分:

  • 演示:

    // Ataching event listener
    let myInput = document.querySelector('.search');
    //setup before functions
    let typingTimer;
    let doneTypingInterval = 500;
    let searchElement = document.querySelector('.items');
    let sorryItemElement = '<div class="sorry-wrapper"><i class="fas fa-truck-loading"></i><a href="#" class="sorry-msg">Sorry, we couldn\'t find anything :(</a><div>';
    let loadingItemElement = '<div class="loading"><i class="fas fa-spinner"></i> Loading...</div>';
    // keyup event would be better, but it doesn't recognize backspace because backspace it's not printable key
    myInput.addEventListener('keydown', () => {
        clearTimeout(typingTimer);
        if (myInput.value) {
            typingTimer = setTimeout(searchBodyTitle, doneTypingInterval);
        }
    });
    
    
    async function searchBodyTitle() {
        const query = myInput.value;
        // early return
        if (query === '') {
            clearItems();
            return;
        }
    
        try {
            startLoading();
            const result = await fetch(`https://jsonplaceholder.typicode.com/posts?q=${query}`);
            const data = await result.json();
            const posts = data.map(post => {
                return {
                    title: post.title,
                    body: post.body
                }
            });
            finishLoading();
            if (posts.length === 0) {
                searchElement.innerHTML += sorryItemElement;
            } else {
                posts.forEach(post => {
                    let slicedTitle = post.title.slice(0, 30);
                    let slicedBody = `${post.body.slice(0, 50)} ...`;
                    newElement(slicedTitle, slicedBody);
                });
            }
            return data;
        } catch (error) {
            finishLoading();
            console.log(error);
        }
    }
    
    function clearItems() {
        searchElement.innerHTML = '';
    }
    
    function newElement(title, body) {
        let newElement = `<a href="#" class="item-options"><span class="dropdown-title">${title}</span><span class="dropdown-body">${body}</span></a>`;
        searchElement.innerHTML += newElement;
    }
    
    function startLoading() {
        clearItems();
        searchElement.innerHTML += loadingItemElement;
    }
    
    function finishLoading() {
        clearItems();
    }
    
    function boldSearchedWord() {
        let titles = document.querySelectorAll('.dropdown-title');
       
    }