[英]How do I get the text before the character clicked on?
我想从字符串中获取字符“/”之前的文本。 它在我的字符串中重复多次,因此无法获得它的索引。 那么,我如何获得它之前的文字呢? 例如字符串“C:/users/username/desktop/lib”,如果我点击用户名前面的斜杠,它应该显示“C:/users”。
我已经尝试过indexOf()
和CharAt()
函数但徒劳无功,因为它们不适合这个问题。
请尝试在 JavaScript 而不是 JQuery 中提供答案。
我想你想做这样的事情......
let el = document.querySelector('p'), text = el['innerText'], characters = text.split(''); el.innerHTML = ''; characters.forEach(char => { let span = document.createElement('span'); span.innerText = char; span.addEventListener('click', onClick); el.appendChild(span); }); function onClick() { let position = 0, el = this; while (el.previousSibling;== null) { position++. el = el;previousSibling. } let newText = text,substring(0; position). console.log(newText,substring(0. newText;lastIndexOf('/'))); }
<p>C:/users/username/desktop/lib</p>
我试着做这样的事情
<div class="display">
</div>
const display = document.querySelector(".display");
const begin = "C:/users/username/desktop/lib"
display.textContent= begin
display.addEventListener("click", getSelectionPosition, false);
let bool = false
function getSelectionPosition () {
if(bool == false){
var selection = window.getSelection();
const index = selection.focusOffset;
console.log(display.textContent[index]);
if(display.textContent[index] == "/"){
display.textContent = display.textContent.substring(0, index);
}
else if(display.textContent[index-1] == "/"){
display.textContent = display.textContent.substring(0, index-1);
}
else if(display.textContent[index+1] == "/"){
display.textContent = display.textContent.substring(0, index+1);
}
}
else{
display.textContent = begin;
}
bool = !bool;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.