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
3 Answers
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
版权声明:本文标题:javascript - Accessing script block with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745567212a2663833.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论