简体   繁体   English

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

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

EDIT: 编辑:

I was trying to pass a reference to an object to another file. 我试图将对对象的引用传递给另一个文件。 The answer seems to be to keep everything in one file and use different modals for different views. 答案似乎是将所有内容保存在一个文件中,并对不同的视图使用不同的模式。


What works: 什么有效:

I'm passing an object to a function via an onClick event and everything works fine. 我通过onClick事件将对象传递给函数,并且一切正常。

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

Now, I'm trying to send the same data to a new page. 现在,我正在尝试将相同的数据发送到新页面。 I put the key information into a query string, parse it and send it to the function but ... it doesn't work. 我将关键信息放入查询字符串中,对其进行解析并将其发送给函数,但是...不起作用。

When clicking on a link on the first page I pass a query string to the second page and then parse it 当单击第一页上的链接时,我将查询字符串传递给第二页,然后对其进行解析

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

and then send it to the function 然后发送给函数

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

The first line on the console panel is this console.log (it's from state2-large.html) 控制台面板的第一行是该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;

The above variables (getYear and getOffice) are getting information from the following object: 上面的变量(getYear和getOffice)正在从以下对象获取信息:

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

The console panel below shows the two console.log calls Notice they are strings. 下面的控制台面板显示了两个console.log调用。请注意,它们是字符串。 The error msg shows that the function was unable to read year in the getYear variable. 错误消息msg表明该函数无法读取getYear变量中的年份。

And below that is what is passed when I send the information via the onClick event (shown above) it sends an object. 下面是当我通过onClick事件(如上所示)发送信息时传递的内容,它发送一个对象。

Image below show the console.logs, 下图显示了console.logs,
then the error 然后错误
then what the onClick event sends 然后onClick事件发送的内容

在此处输入图片说明

selected_race is still a string at this point. selected_race仍然是字符串。 Try countyInfo(elections[getElection]) to actually access the object. 尝试countyInfo(elections[getElection])实际访问该对象。

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

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