开发者

Accessing script block with jquery

I have a script block, in the div element which is appended after html response. I want to access this block and call eval() function for this script. How can I access the script block.

I tried $("#divId script") , but it doesn't work.

<div id="divId">
    <script type="text/javascript">
    // some code here开发者_StackOverflow社区
    </script>
</div>


$("#divId script").html()

If you don't trust me, click http://jsfiddle.net/VZfMd/


$("#divId script") works fine for selecting the element, but here's the problem: $("#divId script").text() doesn't work in IE because jQuery isn't set up to handle the cross browser discrepancies of text nodes in script elements.

IE requires that you access the .text property of the script element, other browsers require that you access .textContent. The following works for me:

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

eval(txt);    

Example


Not sure why it doesn't work in jQuery, but plain DOM should work...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜