将 jquery 动态添加到 div

Dynamically adding jquery into div

抱歉,我知道有很多类似的问题,它们对我帮助很大,但我仍然在最后的障碍中失败。

我正在尝试使用以下方法将一些 jQuery 动态添加到 div 中:

function displayPage(position,page){
    // position arrives looking something like '#pageW20' - ignore quotes
    // page arrives looking something like 'pages/benefits.html' - ignore quotes
    var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
    var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
    var str = "<script type='text/javascript'>";
/*  Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script> 
*/
    str += '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()})';
    str += '<';
    str += '/script>';
    alert(str); // Works to here, alert churns out expected output.
    //$('"' + position + '"').append(str); // Tried this, end up with syntax error
    myDiv.appendChild(str); // This gives Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
}

最后两行显示了我在尝试两种不同方法时遇到的错误。任何线索。 感谢您的关注。

更新:这是我在 alert() 阶段在控制台中得到的结果,这正是我所希望的 -

<script type='text/javascript'>$( "#pageW20" ).load("pages/work.html", function(){openLetter()})</script>

更新:现在解决了,感谢@gaetano。我的代码现在看起来像:

function displayPage(position,page){
    var pos = position.substring(1); 
    var myDiv = document.getElementById(pos); 
    myDiv.innerHTML=""; // Remove existing div content
/*  Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script> 
*/
    var str = '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()});';
    console.log(str); 
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.text = str;
    myDiv.appendChild(s);
}

您传递的 str 变量不是节点,而是字符串。首先尝试使用:

var line = document.createElement("p");
line.innerHTML = str;
myDiv.appendChild(line);

我无法理解您为什么要像评论中描述的那样即时创建和附加脚本。

您得到的错误是:

myDiv.appendChild(str);

但是appendChild需要一个节点作为第一个参数。

因此,如果您需要继续朝这个方向前进,您必须创建一个脚本节点元素,然后将其附加到 html,就像我的示例中那样:

function displayPage(position, page) {
  var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
  var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
  var str = '$( ' + '"' + position + '"' + ' ).load("' + page + '", function(){openLetter()})';
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.text = str;
  myDiv.appendChild(s);
}

displayPage('_XXX', 'page');

console.log(document.getElementById('XXX').outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="XXX"></div>