代码之家  ›  专栏  ›  技术社区  ›  penguru

使用jquery访问脚本块

  •  1
  • penguru  · 技术社区  · 14 年前

    我在div元素中有一个脚本块,附加在html响应之后。我想访问这个块并为此脚本调用eval()函数。如何访问脚本块。

    我试过了 $("#divId script") ,但不起作用。

    <div id="divId">
        <script type="text/javascript">
        // some code here
        </script>
    </div>
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   umpirsky    14 年前
    $("#divId script").html()
    

    如果你不相信我,点击 http://jsfiddle.net/VZfMd/

        2
  •  3
  •   Andy E    14 年前

    $("#divId script") $("#divId script").text() 在IE中不起作用,因为jQuery没有设置为处理脚本元素中文本节点的跨浏览器差异。

    IE要求您访问 属性,其他浏览器要求您访问 . 以下是我的作品:

    var scr = $("#divId script")[0],
        txt = "textContent" in scr ? scr.textContent : scr.text;
    
    eval(txt);    
    

    Example

        3
  •  1
  •   Jhong    14 年前

    $(document.getElementById('divId').getElementsByTagName('script')[0])