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

Categories

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

html - Javascript does not work when activated by element produced by javascript


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

1 Answer

0 votes
by (71.8m points)

Please change code with following code.

From

$('.newdiv>td').click(function(){
    var range = document.createRange();
    range.selectNodeContents(this);  
    var sel = window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(range);
    insertAtCaret('result', sel);return false;
});

To

$(document).on('click', '.newdiv>td', function(){
    var range = document.createRange();
    range.selectNodeContents(this);  
    var sel = window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(range);
    insertAtCaret('result', sel);return false;
});

Reference answer

<button onclick="myfunction()">show</button>
<div id="show"></div>
<br><textarea class="txta" id="result"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function myfunction(){
document.getElementById('show').innerHTML = `
<table><tbody><tr class="newdiv"><td style="background:yellow">enter</td></tr></tbody></table> click the yellow box!
`;
}
// the script below enables typing 'enter' into textarea by clicking the yellow box.
$(document).on('click', '.newdiv>td', function(){
    var range = document.createRange();
    range.selectNodeContents(this);  
    var sel = window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(range);
    insertAtCaret('result', sel);return false;
});
function insertAtCaret(areaId, text) {
  var txtarea = document.getElementById(areaId);
  if (!txtarea) {
    return;
  }
  var scrollPos = txtarea.scrollTop;
  var strPos = 0;
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
    "ff" : (document.selection ? "ie" : false));
  if (br == "ie") {
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart('character', -txtarea.value.length);
    strPos = range.text.length;
  } else if (br == "ff") {
    strPos = txtarea.selectionStart;
  }
  var front = (txtarea.value).substring(0, strPos);
  var back = (txtarea.value).substring(strPos, txtarea.value.length);
  txtarea.value = front + text + back;
  strPos = strPos + text.length;
  txtarea.scrollTop = scrollPos;
}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...