Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Whatever is worth doing is worth doing well
页面上的英语句子,我用鼠标选中某个单词只有跳转到 dialog 图中会高亮 当前选中的单词

现在问题是,当一个句子中如果有多个相同的单词的时候,如何高亮匹配选中的具体的那一个呢

val.content 从字符串变成一个数组

["", "", "Whatever", "is", "worth", "doing", "is", "worth", "doing", "well", "."]

image.png

//现在的实现思路是 不管选中那个都是高亮第一个
`
let index = index = (val.content.split(" ")|| []).findIndex((item) => item === word);
`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
916 views
Welcome To Ask or Share your Answers For Others

1 Answer

findIndex找到了就会返回,所以就是第一个,我觉得你这个在选中的时候就可以给个标示,找出目前选中的索引,然后在弹窗中就可以根据这个索引直接找到目标单词;楼上的给出了找到索引的方法,你可以直接匹配索引值

// 这个方法是找到索引和当前索引值
function findTarget(content, word) {
    return content.reduce((arr, item, index) => {
        if (item == word) {
            let obj = { value: item, index }
            arr.push(obj)
            return arr
        }
        return arr
    }, [])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...