简体   繁体   English

从JavaScript中的另一个函数调用变量

[英]Calling variable from another function in javascript

I have a variable that I would like to use in another function but do not know how to call it correctly. 我有一个要在其他函数中使用的变量,但不知道如何正确调用它。 External JS file: 外部JS文件:

<script>
function search ()
{
var subscriptionId = "";

if (document.getElementById('deleteyes').checked)
 {
  alert(subscriptionId);
 }
}
<script>

HTML file: HTML档案:

<script>
$(document).ready(function() { 
    $.getJSON(ravenUrl + '/indexes/dynamic/Subscriptions?query=Email%253A' + email, function(json) {
        subscriptions = json.Results;
        var html = '';
        for (var i in json.Results) {
            html += '<option value="' + i + '">Edit "' + json.Results[i].Name + '"</option>';
        }
        $('#subscriptionSelector').append(html);
    });

    $("#subscriptionSelector").change(function() { //alert('#forumSelector');
    var subscriptionIndex = $(this).val();
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    alert(subscriptionId);
    });
}
</script>



    <body>
<script type="text/javascript" src="externaljsfile.js"></script>
                                                        <p>create / edit subscription</p>
                                                            <select id="subscriptionSelector"><option selected="true" value="-1">Create new</option></select>
                                                <p>delete subscription</p>
     <div style="margin-left:35px;margin-top:6px;float:left;"><input type="radio" name="delete" id="deleteno" class="div1" checked />no</div>
    <div style="margin-left:35px;margin-top:6px;float:left;"><input type="radio" name="delete" id="deleteyes" class="div1"/>yes</div>

        </body>

The alert(subscriptionId) is generated correctly in the javascript from the html file but the alert in the external js file is obviously not generating the correct subscriptionId. alert(subscriptionId)是在html文件中的javascript中正确生成的,但外部js文件中的警报显然未生成正确的subscriptionId。

I realize that this might be a very simple problem but I am at a skill level where I can't even perform searches to find answers on problems related to javascript so please be patient. 我意识到这可能是一个非常简单的问题,但是我的技能水平是我什至无法执行搜索来找到与javascript相关的问题的答案,因此请耐心等待。 Thank you in advance. 先感谢您。

The most simple solution would be to declare subscriptionId in a global scope. 最简单的解决方案是在全局范围内声明subscriptionId

That means "outside of search() ": 这意味着“在search() ”:

var subscriptionId = "";

function search ()
{

if (document.getElementById('deleteyes').checked)
 {
  alert(subscriptionId);
 }
}
subscriptionId = "what?";
search();

Put the variable declaration outside of a function var subscriptionId = ""; 将变量声明放在函数var subscriptionId = ""; (Global Variable) (全局变量)

Then you could access this from any other function. 然后,您可以从任何其他功能访问它。

The issue here is one of scopes, you're (rightly) declaring subsriptionId in a function scope. 这里的问题是作用域之一,您(正确)在函数作用域中声明subsriptionId As soon as that function returns, though, that variable is GC'ed ( Garbage Collected ). 但是,一旦该函数返回,该变量就会被GC'ed( Garbage Collected )。

As @GungFoo said, at first, you might think that declaring the variable globally, (and thus never have the var GC'ed) would fix things, and it would, at first. 正如@GungFoo所说,起初,您可能会认为全局声明变量(因此永远不会使用var GC)会解决问题,并且起初会解决问题。 But pretty soon you'll pollute the global scope to such an extend that you'll run into issues. 但是很快您将污染全球范围,以至于遇到问题。 You could, inadvertently, change the value of a variable on which another function relies, for example. 例如,您可能无意中更改了另一个函数所依赖的变量的值。 Just google a few articles on the matter, you'll soon find out why this isn't a good idea. 只需在Google上搜索几篇有关此事的文章,您很快就会发现为什么这不是一个好主意。

A few alternatives: 一些替代方案:

Assuming the "other function" is defined in the global scope, you could assign it a property: 假设在全局范围内定义了“其他功能”,则可以为其分配一个属性:

function()
{//this declares and assigns subscriptionId
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    theOtherFunction.subscId = subscriptionId;//assign property
    alert(subscriptionId);
}
//the other one
function theOtherFunction()
{
    alert(theOtherFunction.subscId);//will alert the correct value
}

even simpler would be, simply to use the jQuery: 甚至更简单的是,只需使用jQuery:

function theOtherFunction()
{
    var id = subscriptions[$("#subscriptionSelector").val()]["@metadata"]["@id"].substring(7);
    alert(id);//will work, too
}

The downside of the latter being that the DOM will be scanned on each call, to find that particular element ( $("#subscriptionSelector") ). 后者的缺点是将在每次调用时扫描DOM,以找到该特定元素( $("#subscriptionSelector") )。 To fix that, you can use a closure: 要解决此问题,您可以使用闭包:

var theOtherFunction = (function(selector)//takes DOM element as argument
{
    return function()//this is the actual function
    {//thanks to closures, selector will not be GC'ed
        var id = subscriptions[selector.val()]["@metadata"]["@id"].substring(7);
        alert(id);//works like a charm
    };
})($("#subscriptionSelector"))//pass DOM element as argument

The last approach might seem a bit daunting at first, but spend some time reading up on IIFE, closures and scope wizardry. 刚开始时,最后一种方法似乎有些令人生畏,但要花一些时间来阅读IIFE,闭包和范围向导。 It's one of the best features of JS, very powerful, not that hard once you grasp the basic concepts, too! 它是JS的最佳功能之一,功能非常强大,一旦掌握了基本概念也就不那么难了!

The best solution would be to pass the subscriptionID over to the search function. 最好的解决方案是将subscriptionID传递给search功能。 If this is not possible, you would have to push it into a higher scope (eg global scope). 如果不可能,则必须将其推入更高的范围(例如,全局范围)。

To make it globally available, change this: 要使其全局可用,请更改此设置:

var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);

To this: 对此:

window.subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);

Then it will be available in the external javascript as well. 然后,它也将在外部javascript中可用。

subscriptionId is available in the functions scopes only subscriptionId仅在功能范围内可用

Move var subscriptionId = ""; 移动var subscriptionId = ""; bevore $(document) in the html file html文件中的$ {document)

Replace 更换

<script>
function search ()
{
var subscriptionId = "";

with: 与:

<script>
var subscriptionId = "";
function search ()
{

do : 做:

$("#subscriptionSelector").on('change', function() { //alert('#forumSelector');
    var subscriptionIndex = this.value;
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    $(this).data('checked', subscriptionId); //store as data
    alert(subscriptionId);
});

and then : 接着 :

function search () {
    var subscriptionId = $("#subscriptionSelector").data('checked');
    if ($('#deleteyes').prop('checked')) {
        alert(subscriptionId);
    }
}

That way the data would be stored on the element. 这样,数据将存储在元素上。

More about data() on jQuery : http://api.jquery.com/jQuery.data/ 有关jQuery上的data()更多信息: http : //api.jquery.com/jQuery.data/

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

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