我有两个div(div1和div2)。在div2中,我想指定div1的行号,它应该显示div1的那一行的相关内容。到目前为止,我已经创建了此函数,当我单击Div1中的任何行时,它都可以工作
function getContentOfDiv1() {
var selection = window.document.selection,range, oldBrowser = true;
selection = window.getSelection();
if (!selection) {
range = selection.getRangeAt(0);
oldBrowser = false;
}else {
range = document.selection.createRange();
selection.modify("move", "backward", "lineboundary");
selection.modify("extend", "forward", "lineboundary");
if (oldBrowser) {
var html = document.selection.createRange().htmlText;
range.select();
return html;
}
var html = document.createElement("div");
for (var i = 0, len = selection.rangeCount; i < len; ++i) {
html.appendChild(selection.getRangeAt(i).cloneContents());
}
selection.removeAllRanges();
selection.addRange(range);
return html.innerHTML;
}
document.getElementById("div1").onclick = function(e) {
var html = getContentOfDiv1();
document.getElementById("div1Result").innerHTML = html;
HTML
<div id="div1Result"></div>
<div id="div1">
This is line 1 <br>
This is line 2 <br>
This is line 3 <br>
This is line 4 <br>
This is line 5 <br>
This is line 6 <br>
</div>
<div id="div2">
Specify Line number of div 1
</div>
当我选择Dv1的任何行时,我都能获得Div1的内容。我想要的是当我从div2指定行号时,它应该向我显示Div1的内容。有什么办法吗? 谢谢高级
答案 0 :(得分:0)
点击事件携带的信息不足以传递行号(由 <br>
分隔的字符串定义)。您至少应使用多个div
来达到目标。
这里有一个小片段,可以通过jquery查找行号,也可以使用普通的javascript,但是使用jquery的代码更简单:
$("#lines").click(evt => {
$("#lines").find("div").each((index, elt) => {
if (elt==evt.target) {
console.log("User has clicked on line "+index);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lines">
<div>line 0 (click me!)</div>
<div>line 1 (click me!)</div>
<div>line 2 (click me!)</div>
<div>line 3 (click me!)</div>
</div>