为什么Javascript没有关注动态加载的元素

时间:2016-04-29 06:55:37

标签: javascript ajax

我有一个表单,其中一些元素由ajax根据用户选择加载。我尝试通过javascript在表单中插入一些符号到textarea。我使用inserttext函数的最后聚焦方法。函数只将符号插入textarea但不动态加载textarea.Javascript代码位于正文的末尾。 提前谢谢。

AJAX:

function fetch_no_answer_choice(val){
$.ajax({
type: 'POST',
url: 'fetch_no_answer_choice.php',
data: {'get_option' : val},
success: function (response) {document.getElementById("choice").innerHTML=response;}
});

}

fetch_no_answer_choice.php

<?php
if(isset($_POST['get_option'])){
$choice = $_POST['get_option'];
if ($choice !== 0){ 
$ans = array('A','B','C','D','E','F','G','H','I','J');
$no = 0;    
for ($no = 0; $no<$choice; $no++){
echo'<textarea name = "textarea_'.$ans[$no].'" ></textarea> }
}
exit();
}
?> 

JAVASCRIPT     var lastFocused;     $(“textarea”)。focus(function(){       lastFocused = document.activeElement;     });

function insertText(text) {
  var input = lastFocused;
  console.log(input);

  if (input == undefined) { return; }
  var scrollPos = input.scrollTop;
  var pos = 0;
  var browser = ((input.selectionStart || input.selectionStart == "0") ? 
    "ff" : (document.selection ? "ie" : false ) );
  if (browser == "ie") { 
    input.focus();
    var range = document.selection.createRange();
    range.moveStart ("character", -input.value.length);
    pos = range.text.length;
  }
  else if (browser == "ff") { pos = input.selectionStart };

  var front = (input.value).substring(0, pos);  
  var back = (input.value).substring(pos, input.value.length); 
  input.value = front+text+back;
  pos = pos + text.length;
  if (browser == "ie") { 
    input.focus();
    var range = document.selection.createRange();
    range.moveStart ("character", -input.value.length);
    range.moveStart ("character", pos);
    range.moveEnd ("character", 0);
    range.select();
  }
  else if (browser == "ff") {
    input.selectionStart = pos;
    input.selectionEnd = pos;
    input.focus();
  }
  input.scrollTop = scrollPos;
} 

0 个答案:

没有答案