内嵌jQuery脚本在AJAX调用中不起作用 [英] Inline jQuery script not working within AJAX call
问题描述
我有一个问题:
当我调用一个内嵌的脚本(也使用jQuery)从另一个页面与ajax - 似乎,jQuery没有更多的定义(?),我不能使用任何jQuery函数,应该应用(根据内联脚本)到内容。
I have a issue:
while i call a inline script (wich uses jQuery too) from another page with ajax - it seems, that jQuery is no more defined (?), and I cannot use any of jQuery functions, that should be applied (according to inline script) to content.
它基本上是一个新闻列表,其中包含特定新闻项目的链接。我更喜欢在这个时候使用内联脚本,因为我不需要这个功能。
It's basically a news list, which holds links to particular news items. I prefer using inline-script at this time, because I won't need this functionality elsewhere.
$.ajax({
url: href,
cache: false,
success: function(html){
$('#fancy_ajax').append($(html).find('.mainContentPadded'));
}
});
如您所见,我只是调用另一个页面的一部分,并将其内容附加到页面
As you can see, I'm simply calling a part of another page and appending its contents to page.
当我加载完整的页面(不是它的一部分) - jQuery按预期工作(这就是为什么我遇到这个想法,它需要重新绑定 )
When I load full page (not the part of it) - jQuery works as expected (that's why I came across the idea, that it needs to be "rebinded").
谢谢!
推荐答案
所以如果我明白你的问题正确你有一些JavaScript包含在HTML变量中?如果是这样,它将无法正常工作,因为由于安全风险,从AJAX命中检索到的JavaScript不会被浏览器执行。
So if I understand your question correctly you have some JavaScript contained within the html variable ? If so it will not work, because JavaScript that is retrieved from an AJAX hit is not executed by the browser due to security risks.
我建议您添加必要的JavaScript代码在您的页面中启动Ajax请求,以便在附加新内容时已经可以使用。
I recommend you include the necessary javascript code in your page that is initiating the the Ajax request so that it is already available when you append the new content.
*编辑...
monksp添加了一个很棒的链接作为一个评论,显示如何让jQuery完全符合你想要的。
monksp added a great link as a comment that shows how to have jQuery do exactly what you want.
这里还有一些代码相同但手动:
Here's also some code to do the same but manually:
<html>
<head>
<title>Test JavaScript JSON</title>
</head>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.2');
</script>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('testjs.json', function(json){
$(document.body).append(json.html);
eval(json.js);
});
});
</script>
</body>
</html>
以下是testjs.json的内容:
Here's the content of testjs.json:
{"html":"<p class=\"newelement\">Click me</p>","js":"$(\".newelement\").click(function() { alert($(this).text()); });"}
最后还有一堆存在的插件和其他东西来动态地包含javascript。我以前用过YUI Get: http://developer.yahoo.com/yui/3 / get /
And finally there are a bunch of existings plugins and other things to include javascript dynamically. I used YUI Get in the past: http://developer.yahoo.com/yui/3/get/
这篇关于内嵌jQuery脚本在AJAX调用中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!