首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试从jQuery ajax get响应中选择脚本标记

尝试从jQuery ajax get响应中选择脚本标记
EN

Stack Overflow用户
提问于 2010-12-13 23:58:25
回答 3查看 17.5K关注 0票数 17

我位于A页。单击了一个链接,我通过从B页获取的jQuery get将其加载到DOM中。在B页的DOM中,有多个动态生成的脚本标记,带有类"dataScript“以及一堆我不想用到的其他脚本标记。

只有当它是其他标签时,比如"div“标签。下面是我想要做的一个例子:

第A页:

代码语言:javascript
运行
复制
<html>
<head>
<title>Page A</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function() {
 $("#ajaxJsLink").click(function() {
  $.get("pageB.html", function(data) {
   var scriptElements = $(data).find(".dataScript").contents();
   console.log(scriptElements);
   $(scriptElements).each(function(index) {
    $("#scriptOutput").append($(this).html());
   });
  });
  return false;
 });
 $("#ajaxDivsLink").click(function() {
  $.get("pageB.html", function(data) {
   var scriptElements = $(data).find(".dataDiv").contents();
   console.log(scriptElements);
   $(scriptElements).each(function(index) {
    $("#divOutput").append($(this).html());
   });
  });
  return false;
 });
});
</script>
</head>
<body>
<p>This is page A.</p>
<hr />
<p>
<a href="pageB.html" id="ajaxJsLink">Get JavaScript from Page B.</a><br />
<a href="pageB.html" id="ajaxDivsLink">Get Divs from Page B.</a>
</p>
<hr />
<div id="scriptOutput">
 <h2>Script Output</h2>
</div>
<div id="divOutput">
 <h2>Div Output</h2>
</div>
</body>
</html>

页面B:

代码语言:javascript
运行
复制
<html>
<head>
<title>Page B</title>
</head>
<body>
<p>This is page B.</p>
<div id="scripts">
 <script type="text/javascript" class="dataScript">
  function someFunction() {
   alert("I am");
  }
 </script>
 <script type="text/javascript" class="dataScript">
  function anotherFunction() {
   alert("Javascript");
  }
 </script>
</div>
<div id="divs">
 <div class="dataDiv">
  <div>
   function someFunction() {
    alert("I am");
   }
  </div>
 </div>
 <div class="dataDiv">
  <div>
   function anotherFunction() {
    alert("Html");
   }
  </div>
 </div>
</div>
</body>
</html>

我尝试将.contents()、.html()和.text()附加到.dataScript内容中,但似乎都不起作用。感谢您在查看/回答我的问题时给予考虑。非常感谢您的帮助!

更新:

以防其他人尝试这样做,这里是我最终得到的不太优雅但功能齐全的解决方案:

在Page B上的一个div (带有ID并设置为display:none)中,将javascript作为常规文本(无脚本标记)输出。然后,在Page A上,在get请求的回调函数中执行以下操作:

代码语言:javascript
运行
复制
var docHead = document.getElementsByTagName("head")[0]; //head of Page A
var newScript = document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.innerHTML = jQuery(data).find("#divWithPlainTextJs").text(); //insert plain text JS into script element
docHead.appendChild(newScript); //append script element to head of Page A
jQuery("#divWithPlainTextJs").remove(); //remove the plain text div and JS from the DOM

感谢Emmett提醒我使用document.createElement方法。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4430707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档