简体   繁体   English

防止jQuery()执行javascript

[英]Prevent jQuery() from executing javascript

I am working on some code that uses jQuery to parse data out of html documents from the web. 我正在研究一些使用jQuery解析来自Web的html文档中的数据的代码。 This decision was made because jQuery, with its awesome ability to select objects on a page, makes it excellent for parsing. 之所以做出这个决定是因为jQuery具有在页面上选择对象的强大功能,因此非常适合解析。

The code works like this (where 'html_string' is the html of a whole web page): 代码就像这样(其中'html_string'是整个网页的html):

var page = $(html_string);

The problem I am having is that javascript is being evaluated and executed within the html_string as well. 我遇到的问题是javascript也在html_string中进行评估和执行。 This results in new threads being formed that in some cases, contain infinite loops that make repeated requests to the server and eventually crash the whole client-side of application (not the server). 这导致形成新线程,在某些情况下,包含无限循环,这些循环会向服务器发出重复请求,并最终导致应用程序(而不是服务器)的整个客户端崩溃。

Is there a way to somehow prevent the execution of javascript in this situation. 有没有办法以某种方式阻止在这种情况下执行javascript。 In this situation, the execution of javascript is an unwanted side effect. 在这种情况下,执行javascript是一种不必要的副作用。

Thanks so much! 非常感谢!

Here is a crappy little jsfiddle that shows you the js does not run when you load the html_string into $. 这是一个糟糕的小jsfiddle,它向您显示当您将html_string加载到$时js不会运行。 When you click run you will see an immediate alert 'wtf'. 单击“运行”后,您将看到“wtf”的即时警报。 Three seconds later, the html is loaded into $ and the body is updated to say 'moo', you should not see the alert. 三秒钟后,html被加载到$并且正文更新为'moo',你不应该看到警报。

http://jsfiddle.net/9BAkE/ http://jsfiddle.net/9BAkE/

One way would be to parse the html string befor you wrap it with jQuery. 一种方法是解析html字符串,因为你用jQuery包装它。

Something like: 就像是:

var page = html_string;


//then find the script tag (untested code)
int beginning_of_script = page.indexOf('<script>');
int end_of_script = page.indexOf('</script>');

// remove the script
page = page.remove(beginning_of_script, end_of_script);

You could load this syntax into the browser initially as a comment 您最初可以将此语法作为注释加载到浏览器中

<script>
/* var page = $(html_string); */
</script>

and then extract the contents of the comment later. 然后在以后提取评论的内容。 The advantage here is that the browser is not going to parse and execute the comment on page load. 这里的优点是浏览器不会解析并执行页面加载的注释。

You can also explore using jQuery's .load() function, not sure if that will suit your needs. 您还可以使用jQuery的.load()函数进行探索,不确定它是否符合您的需求。

If you donot care having one extra element, check this! 如果你不小心有一个额外的元素,检查这个! http://jsfiddle.net/UbCFc/4/ http://jsfiddle.net/UbCFc/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM