Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

js 元素在数组中多次出现,如何根据场景确定它的下标实现选中高亮的问题

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);
`


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

1 Reply

0 votes
by (71.8m points)

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
    }, [])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...