简体   繁体   English

将变量从js传递到jquery

[英]pass a variable from js to jquery

wondering how I can pass a variable from load js like: 想知道如何从加载js传递变量,例如:

<script type="text/javascript" src="script.js?myVar=myValue"></script>

and use and pass to script.js itself? 并使用并传递给script.js本身? I Know about declare variable before, but I'm looking for url way. 我之前知道声明变量,但是我在寻找url方式。

Thanks in advance. 提前致谢。

The javascript wont have access to that value. javascript将无法访问该值。 The server would have to look for that and insert that value into the rendered javascript on your behalf. 服务器将不得不寻找该值,并代表您将该值插入呈现的javascript中。

Usually though, the pattern is more like this: 通常,这种模式更像这样:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
  ObjFromScript.myVar = 'myValue';
  ObjFromScript.doStuff();
</script>

You'd have to locate the <script> tag in the document and extract the arguments. 您必须在文档中找到<script>标记并提取参数。 A prominent example of a site using this is facebook with the #xfbml=1 hashtag. 使用此网站的一个突出示例是带有#xfbml=1标签的Facebook。

However, the proper/nice way is not putting any code but functions in script.js and then call someFunction(myValue); 但是,适当/不错的方法不是将任何代码放入函数中,而是将函数放入script.js ,然后调用someFunction(myValue); .

You could do it on the client or the server. 您可以在客户端或服务器上执行此操作。 On the client, get hold of the script element and parse the src attribute. 在客户端上,获取script元素并解析src属性。

<script id="myScript" src="script.js?myVar=foo"></script>
<script>
    var s = document.getElementById('myScript');
    s.src; // parse it and extract myVar
</script>

On the server, setup routes so that script.js goes to some handler written in a server-side language like PHP. 在服务器上,设置路由,以便script.js转到以服务器端语言(如PHP)编写的某些处理程序。 In that case you could be outputting script.js dynamically. 在这种情况下,您可以动态输出script.js Here's an example in PHP. 这是PHP中的示例。

script.js => script.php script.js => script.php

<?php 
    header('Content-Type: application/javascript');
    $myVar = $_GET['myVar'];
?>

// optionally expose myVar inside JavaScript
var myVar = <?php json_encode($myVar) ?>;

// regular JavaScript
alert(myVar);
var x = 10;

You could use document.currentScript , but it isn't widely supported. 您可以使用document.currentScript ,但是它不受广泛支持。

var matches = document.currentScript.src.match(/\?myVar=([^&]+)/),
    myVarParam = matches && matches[1];

Alternatively, you could try getting the script element with the matching URL and parse out the GET param. 或者,您可以尝试获取具有匹配URL的script元素并解析出GET参数。

var scriptPath = 'path/to/this/script.js',
    matches = $('script[src^="' + scriptPath + '"]').attr('src').match(/\?myVar=([^&]+)/),
    myVarParam = matches && matches[1];

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

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