使用JQuery修改外部JS文件 [英] Use JQuery to Modify external JS File

查看:441
本文介绍了使用JQuery修改外部JS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可能,所以如果这个问题有点儿无知,我先向您道歉. 我正在一个必须使用模板的网站,并且不允许使用服务器端语言(例如PHP).网站上有一个我要修改的外部JS文件,但是我无法弄清楚如何使用JQuery从主脚本访问/修改它.

I don't know if this possible so I apologize in advance if this question comes off as being a little ignorant. I am working a website that must use a template and server-side languages such as PHP are disallowed. There is an external JS file on the website that I would like to modify but I cannot figure out how to access/modify it from the main script using JQuery.

如果不清楚,下面是一个示例:

In case that was not clear, here is an example:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="fileToModify.js"></script>
<title>Untitled Document</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>code to modify external file goes here</script>
</body>
</html>

在上面的示例中,我希望能够将代码(用JQuery/JS/类似的其他语言)放在修改外部文件的代码在这里"的位置,并更改"fileToModify"的本地副本. js"(例如,删除其中的一个函数).我知道,如果成功,这种删除将无法更改服务器上托管的实际文件.我只是在尝试在用户下载本地副本时更改本地副本,以更改页面加载后的行为).

In the above example, I would like to be able to place code (in JQuery/JS/some other language like that) where it says "code to modify external file goes here" and alter the local copy of "fileToModify.js" (for example, to delete a function within it). I am aware that, if successful, such a deletion could not alter the real file hosted on the server; I am only trying to alter the local copy when the user downloads it to change how it behaves after the page loads).

使用JQuery/JS/类似的东西可以完成这样的任务吗?

Would such a task be possible with JQuery/JS/something of the sort?

感谢您的帮助

推荐答案

您可以使用ajax获取文件的内容(而不执行文件),然后使用javascript替换某些数据.然后,您可以使用eval来执行它.

You can use ajax to get the contents of the file (and not execute it), then do use javascript to replace some of the data. Then you could use eval to execute it.

$.ajax({
  method: 'GET',
  dataType: 'text',
  url: 'to-modify.js'
}).then(function(data) {
  data = data.replace('bar();', '')
  eval(data)
})

实时演示(点击)

Live demo (click)

这篇关于使用JQuery修改外部JS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆