从脚本元素的src属性分析查询字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从脚本元素的src属性分析查询字符串相关的知识,希望对你有一定的参考价值。

See javadoc style comment in source.
  1. /**
  2.  * Helper object to parse the query string variables from
  3.  * <script> element's src attribute.
  4.  *
  5.  * For example, in test.html:
  6.  *
  7.  * <script src="test.js?name=value"></script>
  8.  *
  9.  * and in test.js, you can get query as name/value pairs:
  10.  *
  11.  * var queries = new ScriptQuery('test.js').parse();
  12.  * for (var name in queries) {
  13.  * var values = queries[name]; // property is Array instance.
  14.  * ...
  15.  * }
  16.  *
  17.  * If you would like to avoid array manipulation.
  18.  * ScriptQuery also provides flatten method, which returns
  19.  * only first value for each properties.
  20.  *
  21.  * var queries = new ScriptQuery('test.js').flatten();
  22.  * for (var name in queries) {
  23.  * alert(queries[name]); // property is simply string
  24.  * }
  25.  */
  26. var ScriptQuery = function(scriptPath) {
  27. this.scriptPath = scriptPath;
  28. }
  29. ScriptQuery.prototype = {
  30. get: function() {
  31. var srcRegex = new RegExp(this.scriptPath.replace('.', '\.') + '(\?.*)?$');
  32. var scripts = document.getElementsByTagName("script");
  33. for (var i = 0; i < scripts.length; i++) {
  34. var script = scripts[i];
  35. if (script.src && script.src.match(srcRegex)) {
  36. var query = script.src.match(/?([^#]*)(#.*)?/);
  37. return !query ? '' : query[1];
  38. }
  39. }
  40. return '';
  41. },
  42. parse: function() {
  43. var result = {};
  44. var query = this.get();
  45. var components = query.split('&');
  46.  
  47. for (var i = 0; i < components.length; i++) {
  48. var pair = components[i].split('=');
  49. var name = pair[0], value = pair[1];
  50.  
  51. if (!result[name]) result[name] = [];
  52. // decode
  53. if (!value) {
  54. value = 'true';
  55. } else {
  56. try {
  57. value = decodeURIComponent(value);
  58. } catch (e) {
  59. value = unescape(value);
  60. }
  61. }
  62.  
  63. // MacIE way
  64. var values = result[name];
  65. values[values.length] = value;
  66. }
  67. return result;
  68. },
  69. flatten: function() {
  70. var queries = this.parse();
  71. for (var name in queries) {
  72. queries[name] = queries[name][0];
  73. }
  74. return queries;
  75. },
  76. toString: function() {
  77. return 'ScriptQuery [path=' + this.scriptPath + ']';
  78. }
  79. }

以上是关于从脚本元素的src属性分析查询字符串的主要内容,如果未能解决你的问题,请参考以下文章

wix - 错误CNDL0004:从命令行运行时,file元素包含意外的属性“src”

30 段 Python 实用代码

即学即用的 30 段 Python 实用代码

javascript高级程序设计(第3版)之《script元素》

img 元素的内容属性

从 DOM 中读取 HTML 片段并向其中添加自定义数据