繁体   English   中英

使用查询字符串时将变量传递给函数不起作用

[英]Passing variable to function doesn't work when using query string

编辑:

我试图将对对象的引用传递给另一个文件。 答案似乎是将所有内容保存在一个文件中,并对不同的视图使用不同的模式。


什么有效:

我通过onClick事件将对象传递给函数,并且一切正常。

$('.senator2016').on("click", function(){
    $('.navSecondary .yr').removeClass("highlight");
    $(this).addClass("highlight");
    countyInfo(elections.election2016senator);
}); 

现在,我正在尝试将相同的数据发送到新页面。 我将关键信息放入查询字符串中,对其进行解析并将其发送给函数,但是...不起作用。

当单击第一页上的链接时,我将查询字符串传递给第二页,然后对其进行解析

    var getElection;
    getElection = window.location.href;
    getElection = getElection.split("?")[1];

然后发送给函数

    console.log(getElection);
    countyInfo(getElection);

控制台面板的第一行是该console.log(来自state2-large.html)

    function countyInfo(selected_race){
          console.log(selected_race);
          var getYear   =   selected_race.electionDetails.year;
          var getOffice =   selected_race.electionDetails.office;

上面的变量(getYear和getOffice)正在从以下对象获取信息:

var elections={
  election2016senator:{
    electionDetails:{
        year:2016,
        office:"Senator",
        caption:"2016 Senatorial Candidates"
    },  

下面的控制台面板显示了两个console.log调用。请注意,它们是字符串。 错误消息msg表明该函数无法读取getYear变量中的年份。

下面是当我通过onClick事件(如上所示)发送信息时传递的内容,它发送一个对象。

下图显示了console.logs,
然后错误
然后onClick事件发送的内容

在此处输入图片说明

selected_race仍然是字符串。 尝试countyInfo(elections[getElection])实际访问该对象。

暂无
暂无

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

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