admin管理员组

文章数量:1432001

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
    </script>
</div>

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
    </script>
</div>
Share Improve this question edited Apr 13, 2011 at 10:43 CommunityBot 11 silver badge asked Aug 10, 2010 at 17:23 pengurupenguru 4,38011 gold badges47 silver badges57 bronze badges 4
  • Isn't the script inside the div already "alive" when the page loads? I wonder why you have to access this script after when you could call the functions and/or variables inside this script from anywhere in the page... – MilkyWayJoe Commented Aug 10, 2010 at 17:30
  • It is "eval'd" automatically after it is appended. If you want to execute the code within <script/> multiple times you should wrap it in a function statement – MooGoo Commented Aug 10, 2010 at 17:32
  • I told the reason, I will call eval(). – penguru Commented Aug 10, 2010 at 17:32
  • If you have to call eval to use the script, why do you have to put it inside a script tag? doesn't it make the script already available to be called anywhere on this document? – MilkyWayJoe Commented Aug 10, 2010 at 17:34
Add a ment  | 

3 Answers 3

Reset to default 3
$("#divId script").html()

If you don't trust me, click http://jsfiddle/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])

本文标签: javascriptAccessing script block with jqueryStack Overflow