简体   繁体   English

从脚本标记中提取src属性并根据特定匹配进行解析

[英]Extract src attribute from script tag and parse according to particular matches

So, I have to determine page type in a proprietary CRM, using JavaScript. 因此,我必须使用JavaScript确定专有CRM中的页面类型。 The only way to determine the page type (that is, the only consistent difference on the front end) is by examining a script tag (out of many list) whose src attribute begins with /modules/. 确定页面类型(即前端唯一一致的差异)的唯一方法是检查src属性以/ modules /开头的脚本标记(在许多列表中)。

In a list of a dozen or so script tags in the header, each page has a line of the following format 在标题中的十几个脚本标记的列表中,每个页面都有以下格式的行

 <script src="/modules/example/includes/sample.js" type="text/javascript"></script> 

Now, the order of the script tag is never the same, but, there's always one script that has /modules/blah. 现在,脚本标记的顺序永远不会相同,但是,总有一个脚本具有/ modules / blah。 I need to extract blah to my script can detect what kind of page it is. 我需要提取blah到我的脚本可以检测它是什么样的页面。

So, how do I, using either JavaScript or jQuery, extract the script tag's src value, where src begins with /modules, and store the value after that ('example', in the example above) as a javascript variable? 那么,我如何使用JavaScript或jQuery提取脚本标记的src值,其中src以/ modules开头,然后将值('示例',在上面的示例中)存储为javascript变量?

Well, you can start by collecting all of the script elements. 好吧,您可以从收集所有脚本元素开始。 With jQuery, that's as simple as 使用jQuery,就像这样简单

var scripts = $("script");

Then limit that set to the elements that have a src attribute: 然后将该set限制为具有src属性的元素:

var scripts = $("script[src]");

...and further limit it to those with a src attribute beginning with "/modules/": ...并进一步将其限制为src 属性以 “/ modules /” 开头的那些:

var scripts = $("script[src^='/modules/']");

...which given your description should result in a set of exactly one element, from which you can now pull the src attribute value itself: ...给出你的描述应该产生一组恰好一个元素,你现在可以从中拉出src属性值:

var path = $("script[src^='/modules/']").attr('src');

Ok, that was easy - now to extract the next part of the path. 好的,这很容易 - 现在提取路径的下一部分。 There are plenty of ways to do this, but split is quick & dumb: create an array of parts using '/' as the separator, then pick off the third element (which will be the one after "modules"): 有很多方法可以做到这一点,但拆分是快速而愚蠢的:使用'/'作为分隔符创建一个零件数组,然后选择第三个元素(将是“模块”之后的那个):

var pathPart = $("script[src^='/modules/']").attr('src').split('/')[2];

Obviously, this is all very specific to the exact format of the script path you're using as an example, but it should give you a good idea of how to begin... 显然,这一切都非常特定于您使用的脚本路径的确切格式作为示例,但它应该让您很好地了解如何开始......

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

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